1. 程式人生 > >MySQL 和 Oracle 主鍵自增長

MySQL 和 Oracle 主鍵自增長

pos tom 速度 mage hone class 緩沖 開始 www

1、MySQL

1)建表

auto_increment:每插入一條數據,客戶表(customers)的主鍵id就自動增1,如下所示

 1 create table customers    -- 創建客戶表
 2 (
 3     id int auto_increment primary key not null,  -- auto_increment:自增長
 4     name varchar(15)
 5 );
 6 

2)測試(實例)

1 insert into customers(name) values("張三"),("李四");-- 向客戶表中插入數據
2 
3
select * from customers; -- 查詢客戶表

技術分享圖片

2、Oracle

1)建表

 1 create table student
 2 (
 3   id       number not null,  -- 主鍵
 4   name     varchar2(20),
 5   birthday  date, 
6 age     number(20),
7
phone varchar2(60),
8
email varchar2(10)
9
)
10 alter table student add constraint student
_pk primary key (id); -- 主鍵

2)創建序列

 1 /*
 2 --創建序列Sequence
 3 create sequence student_id
 4 minvalue 1  --最小值
 5 nomaxvalue  --不設置最大值(由機器決定),或 根據表字段的值範圍設置 maxvalue
6 maxvalue 99999999 -- 最大值
7 start with 1 --從1開始計數,數值可變 8 increment by 1 --每次加1,數值可變 9 nocycle --一直累加,不循環 10 nocache --不建緩沖區,如果建立cache那麽系統將自動讀取cache值個seq,這樣會加快運行速度;如果當機或oracle死了,那麽下次讀取的seq值將不連貫
11 */ 12
13 14 -- 創建序列 15 create sequence student_id 16 increment by 1 17 start with 1;

3)創建觸發器

格式:

  create or replace trigger 觸發器名
  before insert on 表名 for each row when (new.表的自增長字段 is null)
  begin
    select 序列名.Nextval into:new.表的自增長字段 from dual;
  end;
1 -- 創建觸發器 
2 create or replace trigger tg_insertId
3 before insert on student for each row when (new.id is null)
4 begin
5   select student_id.Nextval into:new.id from dual;
6 end;

4)測試(實例)

1 INSERT INTO student(name,birthday,age,phone,email) 
2     VALUES(zhangsan,to_date(2018-01-10 19:55:45,yyyy-MM-dd hh24:mi:ss),18,13510086110,[email protected]);  -- 插入數據
3
4 INSERT INTO student(name,birthday,age,phone,email) 5 VALUES(zhangsan‘,to_date(2018-01-11 19:55:45‘,yyyy-MM-dd hh24:mi:ss‘),20,13510086110‘,[email protected]);

6
7 8 select * from student; -- 查詢學生表

技術分享圖片

作者:DSHORE

出處:http://www.cnblogs.com/dshore123/

歡迎轉載,轉載務必說明出處。(如果本文對你有用,可以點擊一下右下角的 推薦,謝謝!

MySQL 和 Oracle 主鍵自增長