為了確保數據的完整性和唯⼀性,關系型數 據庫通過約束機制來實現目。
一. unique 唯一性約束
值不可重復;
二. not null 非空約束
值不可為空;
三. default 默認值約束
當增加數據時沒有插⼊值時,會自動插⼊默認值;
四. check 檢查約束
mysql不支持該約束,但寫入語句不會報錯;
五. primary key 主鍵約束
主鍵約束 = 唯一性約束 + 非空約束,是一張表的代表性字段,
一張表只能有一個主鍵,
主鍵可以是一個字段,也可以是多個字段(聯合主鍵,復合主鍵),
整形主鍵字段可以使用auto_increment(自動增長)修飾,
插入時不寫主鍵字段值,值 = 上一列值 + 1;
六. foreign key 外鍵約束
外鍵是另一表的主鍵,常用來和其他表建立聯系
外鍵與主鍵的引用類型必須一致,如果主鍵是int外鍵是char則不行
一定要匹配主表中 引用的列 ( 所要創建的外鍵是主表中的主鍵 )
主鍵和外鍵的字符編碼必須一致,如果主表為utf8,則此表也要為utf8
--添加方式
(注:文中添加方式僅為示例,實際同時對一個字段同
時添加多個約束會有bug,具體原因可以參見約束原理)
--第一種,創建表時在修飾字段末直接添加,不支持添加foreign key create table stu(sid int unique,sname char(20));
create table stu(sid int not null,sname char(20));
create table stu(sid int default 0,sname char(20));
create table stu(sid int primary key,sname char(20));
--第二種,創建表時單獨添加,constraint表示起別名,不支持添加default
create table stu(sid int,
sname char(20),
constraint unique_stu unique(sid),
constraint notnull_stu not null(sid),
constraint pk_stu primary key(sid),
constraint fk_stu foreign key(sid) references s(sid)
);
--第三種,表已經存在,且字段下的所有值符合約束條件 alter table stu add constraint unique_stu unique(sid);
alter table stu add constraint notnull_stu not null(sid);
alter table stu add constraint pk_stu primary key(sid);
alter table stu add constraint fk_stu foreign key(sid) references s(sid);
--查詢約束信息,可查看約束名,table表示表名
show keys from table;
--刪除約束,index表示約束名,table表示表名
drop index on table;