1. 程式人生 > 資料庫 >Oracle、MySQL主鍵自增長

Oracle、MySQL主鍵自增長

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序列的建立、修改及刪除 詳解:

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','[email protected]');  
-- 插入資料
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','[email protected]');
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','[email protected]');

在這裡插入圖片描述

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; -- 查詢客戶表

在這裡插入圖片描述