oracle数据库

Oracle数据库使用的也是SQL语言,所以基本的增删改查语句和MySQL是通用的。

1.Oracle的伪列:

rownum,数据库自带的顺序数字

可以使用select rownum from table_name查询

2.表复制

整表复制,将emp表内的字段、数据全部复制到 myemp表:

create table myemp
as select * from EMP

单列复制:

create table myemp as select ename from emp

表结构复制:

create table myemp as select * from emp where 1=2

3.表查询

--连接查询
select * from emp cross join dept
select * from emp,dept

内连接查询:

--内连接
select * from emp join dept on emp.deptno=dept.deptno
select * from emp,dept where emp.deptno=dept.deptno

全连接查询:

查询左右两表中复合条件的数据与不符合条件的数据

--全连接查询
select * from dept full join emp on emp.deptno=dept.deptno;

表别名:

--表别名
select * from emp a join dept b on a.deptno=b.deptno

视图查询:

可以把查询结果当成一张表来执行查询

create view t as select dname from dept;
select * from t;

 将子查询结果当做表来查询:

select ename from (select * from emp inner join dept on emp.deptno=dept.deptno);

利用rownum来分页

select * from (select rownum as nid,empno,ename,job,mgr,hiredate,sal,comm,deptno from emp ) where nid between 1 and 5;

集合操作:

UNION 操作符返回两个查询的不重复的所有行。

INTERSECT 操作符只返回两个查询的公共行。

MINUS 操作符返回从第一个查询结果中排除第二个查询中出现的行。

字符串拼接:

select empno||'   '||ename 姓名 from emp;--字符拼接

4.查询系统时间

--查询当前系统时间 dual 虚拟表
select sysdate from dual;
select systimestamp from dual;

5.建表

这里要注意Oracle的数据类型不同于MySQL:

复制代码
--建表
create table student(
    sid number primary key,
    sname varchar2(10) not null,
    ssex char(2) check(ssex in ('男','女')),--检查约束
    sbirthday date default(sysdate),--缺省约束
    sidcard varchar2(18) unique,--唯一约束
    cid number,
    constraint fk_cid foreign key(cid) references course(cid) --外键约束
);
复制代码

格式化日期格式:

TO_DATE

insert into student values(student_seq.nextval,'李四','男',TO_DATE('1993-02-04','YYYY-MM-DD'),'123466787987',2);--指定日期格式插入

格式化字符串:

select TO_CHAR(0.123,'$0.999') from dual; //$0.123

自增序列:

复制代码
--序列
create sequence test_sequence
       start with 1 --指定第一个序号从几开始
       increment by 1 --指定序号之间的间隔
       maxvalue 1000 --表示序列的最大值为
       minvalue 1 --表示序列的最小值
       nocycle --在达到最大值后停止
       cache 30 --指定内存中预先分配的序号数 
create table test(
       tid number primary key,
       tname varchar2(20)
);
insert into test values(test_sequence.nextval,'张三');
select test_sequence.currval from dual;--查询序列当前值
复制代码
drop sequence test_sequence;--删除序列

 注意,当序列删除再重新创建,开始值变为一,如果此时表中已有主键为1的数据,使用该序列插入数据,序列会自动从2开始,不会报主键重复错误。

6.添加约束

复制代码
create table score(
       sid number,
       sname varchar2(10)
);

alter table score add constraint pk_score primary key(sid);--添加约束
alter table score add constraint nn_sname unique(sname);
复制代码

7.将其他表的数据插入到当前表

create table studentC as select * from student where 1 = 2;--表结构复制
insert into studentC select * from student where sid=1;--将其他表中的数据插入当前表(前提:拥有相同表结构)
原文地址:https://www.cnblogs.com/jason111/p/9166148.html