Primary Key
在物理層面上,主鍵有兩個用途:
惟一地標識一行
作為一個可以被外鍵有效引用的對象
注意:
1.類似于索引,表中每一行都有一個唯一標識自己的索引.不允許有NULL值.
2.永遠也不要更新MySQL主鍵
- 主鍵不應包含動態(tài)變化的數(shù)據(jù)
4.主鍵應當由計算機自動生成
- 聲明方法:
創(chuàng)建表時 :
create table students , primary key();
創(chuàng)表后設置主鍵
alter table customers add primary key();
主鍵自動增長在Mysql,SqlServer,Oracle中的設置
- 把id設為auto_increment類型,mysql數(shù)據(jù)庫會自動按遞增的方式為主鍵賦值。
create table customers(id int auto_increment primary key not null, name
varchar(15));
insert into customers(name) values("name1"),("name2");
select id from customers;
查詢結(jié)果:
id
1
2
在SQLServer中,如果把表的主鍵設為identity類型,數(shù)據(jù)庫就會自動為主鍵賦值
create table customers(id int identity(1,1) primary key not null, name
varchar(15));
insert into customers(name) values("name1"),("name2");在Oracle中,可以為每張表的主鍵創(chuàng)建一個單獨的序列,然后從這個序列中獲取自動增加的標識符,把它賦值給主鍵
create sequence customer_id_seq increment by 2 start with 1
一旦定義了customer_id_seq序列,就可以訪問序列的curval和nextval屬性。
curval:返回序列的當前值
nextval:先增加序列的值,然后返回序列值
如: 創(chuàng)建一個名為customer_id_seq的序列,這個序列的起始值為1,增量為1
create table customers(id int primary key not null, name varchar(15));
insert into customers values(customer_id_seq.curval, "name1")(customer_id_seq.nextval, "name2");