Oracle、MySQL主键自增长
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Oracle、MySQL主键自增长,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2958字,纯文字阅读大概需要5分钟。
内容图文
Oracle
1、建表
create table student
(
id number not null, -- 主键
name varchar2(20),
birthday date,
age number(20),
phone varchar2(60),
email varchar2(10)
)
alter table student add constraint student_pk primary key(id); -- 主键
2、创建序列
Oracle中的序列并不是和MySQL中的自增长一样,连续性的,而是跳跃、不连续性的。如要使他连续,则必须指定相关的属性和值。
/*
--创建序列Sequence
create sequence student_id
minvalue 1 --最小值
nomaxvalue --不设置最大值(由机器决定),或 根据表字段的值范围设置maxvalue
maxvalue 99999999 -- 最大值
start with 1 --从1开始计数,数值可变
increment by 1 --每次加1,数值可变
nocycle --一直累加,不循环
nocache; --不建缓冲区。
如果建立cache那么系统将自动读取cache值个seq,这样会加快运行速度;如果在单机中使用cache,或者oracle死了,那么下次读取的seq值将不连贯,所以不建议使用cache。
*/
-- 创建序列
create sequence student_id 16 minvalue 1
maxvalue 999
increment by 1
start with 1
nocycle
nocache;
Oracle sequence序列的创建、修改及删除 详解:http://www.cnblogs.com/dshore123/p/8269537.html
3、创建触发器 (以下三种方式都行)
格式:
create or replace trigger 触发器名
before insert on 表名
for each row
when (new.表的自增长字段 is null)
begin
select 序列名.Nextval into:new.表的自增长字段 from dual;
end;
-- 方式一
create or replace trigger tg_insertId
before insert on student
for each row
when (new.id is null) -- 当id为NULL时触发
begin
select student_id.Nextval into:new.id from dual;
end;
-- 方式二 (我比较喜欢这种)
create or replace trigger tg_insertId
before insert on student
for each row
begin
select student_id.Nextval into:new.id from dual;
end;
-- 方式三
create or replace trigger tg_insertId
before insert on student for each row
declare -- 声明
-- 局部变量(student表里的字段)
begin
if updating then
insert into student
values(student_id.nextval,
:old.name, -- 对应student表中的字段
:old.birthday,
:old.age,
:old.phone,
:old.email
);
end if;
end;
4、测试(实例)
由于创建了触发器,所以下面的插入语句,不需要再写上id这一项
INSERT INTO student(name,birthday,age,phone,email)
VALUES('zhangsan',to_date('2018-01-10 19:55:45','yyyy-MM-dd hh24:mi:ss'),18,'13510086110','123456789@qq.com');
-- 插入数据
INSERT INTO student(name,birthday,age,phone,email)
VALUES('zhangsan',to_date('2018-01-11 19:55:45','yyyy-MM-dd hh24:mi:ss'),20,'13510086110','123456789@qq.com');
select * from student; -- 查询学生表
or
insert into student(seq,name,birthday,age,phone,email) -- 这是带上“自增长主键(seq)”的写法
values(student_id.Nextval,'zhangsan',to_date('2018-01-10 19:55:45','yyyy-MM-dd hh24:mi:ss'),18,'13510086110','123456789@qq.com');
MySQL
1、建表
auto_increment:每插入一条数据,客户表(customers)的主键id就自动增1,如下所示
create table customers -- 创建客户表
(
id int auto_increment primary key not null, -- auto_increment:自增长
name varchar(15)
);
2、 测试(实例)
insert into customers(name) values("张三"),("李四");-- 向客户表中插入数据
select * from customers; -- 查询客户表
内容总结
以上是互联网集市为您收集整理的Oracle、MySQL主键自增长全部内容,希望文章能够帮你解决Oracle、MySQL主键自增长所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。