溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

mysql建立約束的方法

發(fā)布時(shí)間:2020-10-09 19:10:08 來源:億速云 閱讀:170 作者:小新 欄目:MySQL數(shù)據(jù)庫

這篇文章將為大家詳細(xì)講解有關(guān)mysql建立約束的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

方法: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

關(guān)于mysql建立約束的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI