方法:1、在創(chuàng)建表時(shí),在字段后使用primary key和foreign key關(guān)鍵字建立主鍵和外鍵約束;2、在建表后,通過“alter table”語句配合primary key、not null、unique等關(guān)鍵字來建立約束。
MYSQL添加約束
第一種:創(chuàng)建表的時(shí)候
create table table_name( 列名1 數(shù)據(jù)類型 (int) primary key auto_increment, 列名2 數(shù)據(jù)類型 not null, 列名3 數(shù)據(jù)類型 unique, 列名4 數(shù)據(jù)類型 default '值', constraint 索引名 foreign key(外鍵列) references 主鍵表(主鍵列) on delete cascade | on delete set null )
第二種:建表完成之后
1.主鍵約束 添加:alter table table_name add primary key (字段) 刪除:alter table table_name drop primary key 2.非空約束 添加:alter table table_name modify 列名 數(shù)據(jù)類型 not null 刪除:alter table table_name modify 列名 數(shù)據(jù)類型 null 3.唯一約束 添加:alter table table_name add unique 約束名(字段) 刪除:alter table table_name drop key 約束名 4.自動(dòng)增長 添加:alter table table_name modify 列名 int auto_increment 刪除:alter table table_name modify 列名 int 5.外鍵約束 添加:alter table table_name add constraint 約束名 foreign key(外鍵列) references 主鍵表(主鍵列) 刪除: 第一步:刪除外鍵 alter table table_name drop foreign key 約束名 第二步:刪除索引 alter table table_name drop index 索引名 [^1]: 約束名和索引名一樣 6.默認(rèn)值 添加:alter table table_name alter 列名 set default '值' 刪除:alter table table_name alter 列名 drop default