公司现在项目数据库使用oracle,oracle实现表主键自增比mysql麻烦
mysql 在表主键auto_increment 打钩即可。oracle没有改属性,就相对麻烦。特此记录一下自增方法
测试案例如下
第一步创建一张测试表table1
sql语句
create table table1
(
id int not null,
name varchar2(20),
sex varchar2(4)
)
添加表注释、字段注释
comment on table table1 is '测试表 稍后会删除'
comment on column table1.name is '姓名'
comment on column table1.sex is '性别'
第二步:创建序列
create sequence table1_id
minvalue 1 //自增字段最小值
nomaxvalue //最大值 没有就算nomaxvalue
increment by 1 //每次增值1
start with 1 //起始值
nocache; //不缓存
第三步:创建触发器
create or replace trigger table1_tg_insertId
before insert on table1 for each row
begin
select table1_id.nextval into:new.id from dual;
end;
第四步:测试开始 插入两条数据
insert into table1(name,sex) values ('zhangsan','nan');
insert into table1(name,sex) values ('lisi','nan');
完整版
create table t_test(
id int not null,
name varchar2(20),
sex varchar2(4)
)
comment on table t_test is '测试表 稍后会删除'
comment on column t_test.name is '姓名'
comment on column t_test.sex is '性别'
create sequence t_test_id
minvalue 1 --自增字段最小值
nomaxvalue --最大值 没有就算nomaxvalue
increment by 1 --每次增值1
start with 1 --起始值
nocache; --不缓存
create or replace trigger t_test_tg_insertId
before insert on t_test for each row
begin
select t_test_id.nextval into:new.id from dual;
end;
insert into t_test(name,sex) values ('杜甫','nan');
SELECT * from t_test
实现分页
SELECT * FROM(SELECT ID,NAME,row_number() over(ORDER BY id asc) rn FROM "t_user")WHERE rn <=3
SELECT * from (SELECT ID,NAME, row_number() over(ORDER BY id asc) rn FROM "t_user") where rn >40 AND rn <=50
select a.* from ( select * FROM "t_user" where id <= 50 ) a where a.id >= 40;