首頁  >  文章  >  資料庫  >  mysql怎麼添加約束?

mysql怎麼添加約束?

青灯夜游
青灯夜游原創
2019-04-29 14:50:0316017瀏覽

在MYSQL資料庫中,在建表時就可以進行對錶的各項進行一些操作,例如新增主鍵約束或非空約束;也可以在建表後進行新增約束和刪除約束的操作。下面這篇文章就來帶大家具體了解一下,希望對大家有幫助。

mysql怎麼添加約束?

什麼是約束?

約束其實就是表中資料的限制條件;目的是為了保證表中的記錄完整和有效。

常用的約束有:

1、非空約束(not null)

2、唯一約束(unique)

3、主鍵約束( primary key)

4、外鍵約束(foreign key)

5、檢查約束(目前MySQL不支援、Oracle支援)

mysql新增和刪除約束的方法:

1、建立表格的時候加入約束

create table table_name(
列名1  数据类型 (int) primary key auto_increment,
列名2 数据类型  not null,
列名3 数据类型   unique,
列名4 数据类型  default '值',
constraint  索引名 foreign key(外键列)  references 主键表(主键列)
on delete cascade | on delete set null
)

##2、建表完成之後再加入和刪除約束

1)、非空白約束

新增非空約束

alter  table table_name modify 列名 数据类型  not null

刪除非空白約束

alter table table_name modify 列名 数据类型 null

2)、唯一約束

新增唯一約束

alter table table_name add unique 约束名(字段)

刪除唯一約束

alter table table_name drop key 约束名

3)、主鍵約束


新增主鍵約束

alter table  table_name add primary key (字段)

刪除主鍵約束

alter table table_name drop primary key

4)、外鍵約束

新增外鍵約束

alter table table_name add constraint 约束名 foreign key(外键列)

刪除外鍵約束

alter table table_name drop foreign key 约束名

5)、自動成長約束

新增自動成長限制

alter table table_name  modify 列名 int  auto_increment

刪除自動成長限制

alter table table_name modify 列名 int

相關影片教學推薦:《

MySQL教學
#

以上是mysql怎麼添加約束?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn