oracle基本操作

来源:互联网 发布:血族手游 知乎 编辑:程序博客网 时间:2024/05/01 01:06
增加字段

alter table t1 add sex int;


删除字段
drop table t1 drop column sex;

创建序列seq01,从10000000开始,每次自增1
create sequence seq01 start with 10000000 increment by 1;

插入(下一个值.nextval)
insert into t1 values( seq01.nextval, 'zhangsan' );

oracle会自动为每个表增加rownum字段


显示rownum:
select t1.*, rownum from t1;

注意:select *, rownum from t1;这么写是错的,因为*包含除了rownum外所有字段,但不包含rownum字段所以要用t1.*


如果有多层的嵌套查询,每层都有一个rownum

用rn这个名字显示rownum
select t1.*, rownum as rn from t1;


查询嵌套的rownum
select tmp.*, rownum as rn2 from ( select t1.*, rownum as rn from t1 order by id desc ) tmp;


rownum每次都是现编的号,所以当使用rownum执行一个查询的时候,查询结果必须包含第一条,即rownum = 1 或者rownum <= 某值


【利用rownum做翻页】

先插入数据:
create table t1 ( id int, name varchar(30) );
insert into t1 values ( seq01.nextval, 'name1' );
insert into t1 values ( seq01.nextval, 'name2' );
insert into t1 values ( seq01.nextval, 'name3' );
insert into t1 values ( seq01.nextval, 'name4' );
insert into t1 values ( seq01.nextval, 'name5' );
insert into t1 values ( seq01.nextval, 'name6' );
insert into t1 values ( seq01.nextval, 'name7' );
insert into t1 values ( seq01.nextval, 'name8' );
insert into t1 values ( seq01.nextval, 'name9' );




查询第一页:
SQL> select tmp.*, rownum from (select t1.*, rownum as rn from t1 where rownum <= 3 order by id desc) tmp where rownum <= 3 order by rn;


        ID NAME                                   RN     ROWNUM
---------- ------------------------------ ---------- ----------
  10000003 name1                                   1          3
  10000004 name2                                   2          2
  10000005 name3                                   3          1


查询第二页:
SQL> select tmp.*, rownum from (select t1.*, rownum as rn from t1 where rownum <= 6 order by id desc) tmp where rownum <= 3 order by rn;


        ID NAME                                   RN     ROWNUM
---------- ------------------------------ ---------- ----------
  10000006 name4                                   4          3
  10000007 name5                                   5          2
  10000008 name6                                   6          1


查询第三页:
SQL> select tmp.*, rownum from (select t1.*, rownum as rn from t1 where rownum <= 9 order by id desc) tmp where rownum <= 3 order by rn;


        ID NAME                                   RN     ROWNUM
---------- ------------------------------ ---------- ----------
  10000009 name7                                   7          3
  10000010 name8                                   8          2
  10000011 name9                                   9          1


【约束(constraint)】:
主键:primary key
唯一:unique
非空:not null
默认:default '男'

create table t2 ( code int primary key, name varchar(30) unique, age int not null, sex varchar(3) default '男' );

增加一个约束pk_01:(pk_01是约束名字)
alter table t2 add constraint pk_01 primary key (id);

删除一个约束pk_01:
alter table t2 drop constraint pk_01;









0 0