約束
保證數(shù)據(jù)的完整性、一致性、有效性
默認(rèn)約束
- 在插入記錄時,如果不給該字段賦值,則使用默認(rèn)值
字段名 數(shù)據(jù)類型 default 值
非空約束
- 不允許將該字段設(shè)置為
NULL 字段名 數(shù)據(jù)類型 not null
索引
定義
對數(shù)據(jù)庫中表的一列或者多列的值進(jìn)行排序的一種結(jié)構(gòu)(MySQL中用Btree方式)
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn)
- 加快數(shù)據(jù)的檢索速度
- 缺點(diǎn)
- 當(dāng)對表中的數(shù)據(jù)進(jìn)行增加、刪除或修改的時候,索引也得動態(tài)維護(hù),降低了數(shù)據(jù)的維護(hù)速度
- 索引需要占用物理空間
索引示例
# 開啟運(yùn)行時間檢測
set profiling=1;
# 執(zhí)行查詢語句
select name from t1 where name="lucy99999";
# 查看執(zhí)行時間
show profiles;
# 在name字段創(chuàng)建索引
create index name on t1(name);
# 再執(zhí)行查詢語句
select name from t1 where name="lucy88888";
# 查看執(zhí)行時間
show profiles;
索引分類
普通索引 index
- 一個表中可以有多個
index字段 - 字段的值可以有重復(fù),且可以為
null值 - 經(jīng)常把做查詢條件的字段設(shè)置為
index字段 -
index字段的key標(biāo)志是MUL
# 創(chuàng)建index
# 創(chuàng)建表時
create table 表名(...,index(字段名),index(字段名),...);
# 已有表
create index 索引名 on 表名(字段名);
# 查看索引
desc 表名
show index from 表名\G;
# 刪除索引
drop index 索引名 on 表名;
唯一索引 unique key
- 一個表中可以有多個
unique字段 -
unique字段的值不允許重復(fù),但可以為null -
unique的key標(biāo)志是UNI
# 創(chuàng)建唯一索引
# 創(chuàng)建表時創(chuàng)建
create table 表名(...,unique(字段名),unique(字段名),...);
# 在已有表中創(chuàng)建
create unique index 索引名 on 表名(字段名);
# 刪除唯一索引
drop index 索引名 on 表名;
# index,unique在刪除時只能一個一個刪
主鍵索引 primary key
- 一個表中只能有一個主鍵(
primary)字段 - 對應(yīng)字段的值不允許重復(fù),且不能為空
- 主鍵字段的
key標(biāo)志PRI - 把表中能夠唯一標(biāo)識一條記錄的字段設(shè)置為主鍵,通常把表中記錄編號的字段設(shè)置為主鍵
# 創(chuàng)建主鍵索引
# 創(chuàng)建表時
create table 表名(字段名 數(shù)據(jù)類型 primary key [auto_increment],...)
auto_increment = 起始值;
# 已有表
alter table 表名 add primary key(字段名);
# 刪除自增長屬性(modify)
alter table 表名 modify 字段名 數(shù)據(jù)類型;
# 刪除主鍵索引
alter table 表名 drop primary key;
# 已有表添加自增長屬性
alter table 表名 modify 字段名 數(shù)據(jù)類型 auto_increment;
# 已有表重新指定起始值
alter table 表名 auto_increment = 起始值;
外鍵索引 foreign key
- 讓當(dāng)前表字段的值在另一個表的范圍內(nèi)選擇
- 主表、從表字段數(shù)據(jù)類型要一致
- 主表被參考字段:主鍵
# 創(chuàng)建外鍵
foreign key(參考字段名)
references 主表(被參考字段名)
on delete 級聯(lián)動作
on update 級聯(lián)動作
# 在已有表中添加外鍵
# 在已有表中添加外鍵時,會受到表中原有數(shù)據(jù)的限制
alter table 表名 add
foreign key(參考字段名) references 被參考表名(被參考字段名)
on delete 級聯(lián)動作
on undate 級聯(lián)動作
# 查看外鍵名
show create table 表名;
# 刪除外鍵
alter table 表名 drop foreign key 外鍵名;
級聯(lián)動作
-
cascade數(shù)據(jù)級聯(lián)更新- 當(dāng)主表刪除記錄時,如果從表有相關(guān)聯(lián)記錄則級聯(lián)刪除
- 當(dāng)主表更新被參考字段的值時,從表級聯(lián)更新參考字段的值
-
restrict(默認(rèn))- 當(dāng)主表刪除記錄時,如果從表中有相關(guān)記錄則不允許主表刪除
- 當(dāng)主表更新記錄時,如果從表中有相關(guān)記錄則不允許主表更新
-
set null- 當(dāng)主表刪除記錄時,從表中相關(guān)記錄外鍵字段變?yōu)?code>null
- 當(dāng)主表更新記錄時,從表中相關(guān)記錄外鍵字段變?yōu)?code>null
-
no action- 同
restrict,都是立即檢查外鍵限制
- 同