1. 程式人生 > >六項約束

六項約束

保持 關系 實現 主鍵 default 每次 有一個 必須 插入

非空約束

create table 表名(

  id int not null

  );

  

唯一約束

create table 表名(

  id int unique key,

  name varchar(20)

  );

主鍵約束 primary key

主鍵的作用:可以唯一標示一條數據,每張表裏只有一個主鍵。

主鍵的特性:非空唯一。當表裏沒有主鍵時,第一個出現的非空且唯一的列,被當成主鍵。

creat table 表名(

  id int primary key,

  name varchar(20)

  );

刪除主鍵約束:

alter table 表名

  drop primary key;

自增長 auto_increment

自動編號,一般與主鍵組合使用。一個表裏面只能有一個自增長,默認情況下起始值為1,每次增量為1。

create table 表名(

  id int primary key auto_increment,

  name varchar(20)

  )auto_increment = 100;  # 不加auto_increment=100,起始值是1。

默認約束 default

初始值設置,插入記錄時,如果沒有

create table 表名(

  id int primary key auto_increment,

  name varchar(20) not null,

  age int not null default 18

  );

外鍵約束 foreign key

保持數據的一致性,完整性實現一對多關系。外鍵必須關聯到鍵上面去,一般情況是關聯到另一張表的主鍵

foreign key (本列表的字段名) reference 其他表名(要關聯的字段名)

六項約束