MySQL中四種約束簡述。
阿新 • • 發佈:2019-01-06
一.資料的完整性
- 域完整性
- 實體完整性
- 引用完整性
二.約束
1. 非空約束 not null
insert into teacher(id,sex,birthday)
values(1,'male','2018-5-5')
會報錯,因為name項有非空約束
取消非空約束:
alter table teacher modify name vachar(10);
如果要繼續為name加上非空約束,應該先刪掉name的值,然後再執行以下語句,否則會報錯。
alter table teacher modify name varchar(10) not null;
或者:
alter table teacher change name name varchar (10) not null;
2. 唯一約束 unique
create table test_unique(
id int(10),
name varchar(32) not null,
email varchar(128) unique
);
新增資料
insert into test_unique values(1,'zmt','[email protected]')
取消唯一性約束:
語法:alter table 表名 drop index 欄位名;
alter table test_unique drop index email;
建表後新增唯⼀性約束:
語法:alter table 表名 add unique(欄位名)
alter table test_unique add unique(id);
3.主鍵約束
create table test3_primary(
id int not null,
name varchar(50) not null,
primary key(id,name)
);
insert into test3_primary values(1,'abc')
刪除主鍵約束:
語法:alter table 表名 drop primary key;
alter table test3_primary drop primary key;
建表後新增主鍵約束:
語法:alter table 表名 add primary key(欄位名)
alter table test3_primary add primary key(id) ; --將欄位設定為主鍵
4. 預設值約束 default
create table test1_default(
id int not null,
name varchar(50) not null DEFAULT 'abc'
);
插⼊資料的時候,如果不寫⼊name的值,則預設顯示填入abc
刪除預設值約束:
語法:alter table 表名 change 欄位 欄位 欄位型別 not null
alter table test1_default change name name varchar(50) not null
建表後新增預設值約束:
語法:alter table 表名 modify 列名 列型別 not null default ‘預設值’;
alter table test1_default modify name varchar(50) not null default 'abc';
5.外來鍵約束
建表的同時建外來鍵
create table emp(
.......
foreign key(外來鍵欄位) references dept(deptno)
)
建立表之後新增外來鍵
alter table emp add foreign key(deptno) references dept(deptno)
刪除外來鍵:
語法:alter table 表名稱 drop foreign key 外來鍵名稱;
例:alter table empA drop foreign key empa_ibQk_1;
注意:如果沒有在建表的時候標明外來鍵名稱,可以通過:
show create table 表名 進⾏檢視外來鍵名稱;