数据库主键生成策略
数据库中每个表都要有一个主键,主键不应是表中有意义的属性列。
主键唯一不重复不为空。
主键生成策略
- 自动增长:数字
- 随机生成:32位字符串
自动增长
使用序列自增。
/*先创建一个序列,在插入数据时使用序列名.nextval获取序列的值作为主键。*/
create sequence seq_student_id
minvalue 1--最小值
maxvalue 99999--最大值
increment by 1--步长
insert into student(id,name,age) values(seq_student_id.nextval,'lee',20)
使用触发器自动化给主键id自增。
/*为主键创建一个序列*/
create sequence seq_student_id
minvalue 10
maxvalue 99999
increment by 1;
/*使用触发器添加主键自动增长*/
create trigger tri_student_id
/*在对表bank_info进行插入操作前*/
before insert on student
for each row
begin
select seq_student_id.nextval into :new.id from dual;
end;
Mysql数据库在创建数据表时为主键加上auto_increment key
create table user(
uid int auto_increment key primary key
);
随机生成
sys_guid()方法:系统根据当前时间和机器码,生成全球唯一的一个32位序列号。
insert into student(id,name,age) values(sys_guid(),'lee',20)