索引和約束的建立

2021-07-16 13:13:04 字數 2417 閱讀 7079

==>學習彙總(持續更新)

==>從零搭建後端基礎設施系列(一)-- 背景介紹

1.索引

建立索引的語法:create index 索引名 on 表名(欄位1,欄位2,……,欄位n)

例子: create index idx_person_name on person(name);

create index idx_person_nameage on person(name,age);

刪除索引的語法:drop index 索引名 on 表名

例子: drop index idx_person_name on person;

drop index idx_person_nameage on person;

2.約束

1).非空約束

使用not null定義,建立表時預設是允許為空的

例子:create table person(id int not null,name varchar(20));

2).唯一約束

使用unique定義,意思是乙個欄位中不能有兩個值相同

單字段唯一約束:

例子:create table person(id int unique,name varchar(20));

復合字段唯一約束: 復合欄位中單一的字段值可以重複,但是多個字段值不能同時重複

定義復合唯一約束需要定義在所有字段列表之後,語法如下:constraint 約束名 unique(欄位1,……,欄位n)

例子:create table person(

number varchar(20),

departmentnumber varchar(20),

name varchar(20),

age int,

constraint unic_dep_num unique(number,departmentnumber)

);可以在乙個表中新增多個復合唯一約束,只要約束名不一樣就行.

例子:create table person(

number varchar(20),

departmentnumber varchar(20),

name varchar(20),

age int,

constraint unic_1 unique(number,departmentnumber),

constraint unic_2 unique(departmentnumber,name)

);使用alter table語句可以為一張已經存在的資料表新增新的約束

alter table 表面 add constraint 唯一約束名 unique(欄位1,……,欄位n)

例子:alter table person add constraint unic_3 unique(name,age);

alter table 語句也能刪除已經建立好的復合唯一約束

alter table 表名 drop index 唯一約束名

例子:alter table person drop index unic_1;

3).check約束

check約束會檢查輸入到記錄中的值是否滿足乙個條件,如果不滿足這個條件則對資料庫做出的修改不會成功.

注意:mysql中的check只是個修飾作用,並無實際效果

例子:create table person(

number varchar(20),

name varchar(20),

age int check(age>0),

workyear int check(workyear>0)

);還可以命名約束

constraint chk_person check (id_p>0)

撤銷約束

例子:alter table persons

drop check chk_person

4).主鍵約束

主鍵必須能夠唯一標識一條記錄,也就是主鍵欄位中的值必須是唯一的,而且不能包含null值,所以從某種意義來說主鍵約束是uinque約束和非空約束的組合.

例子:create table person(

number varchar(20) primary key,

name varchar(20),

age int

)5).外來鍵約束

語法:foreign key 外來鍵字段 references 外來鍵表名(外來鍵表的主鍵字段)

也可以用alter table語句的方式新增外來鍵約束

alter table book add constraint fk_book_author foreign key(authorid) references author(id);

刪除方式是先刪除引用表,再刪除被引用表.

索引和約束

索引優點 1.索引使得檢索的資料的速度大大加快 2.建立索引時自動新增了唯一性約束,確保每一條資料的唯一性 3.可以加快表與表之間的鏈結,提高多表查詢的速度 4.在分組和排序子句進行資料彙總的時候,顯著減少查詢中分組和排序的時間。每張表都會有乙個rowid實體地址列,用來唯一標誌一條記錄所在物理 位...

索引和約束

一 雖然索引引用可以提高資料的查詢速度,但是任何事物都有雙刃劍,它也有一些缺點 1 索引會佔據一定的磁碟空間,就像有安筆劃的查詢的目錄的書會比沒有這種目錄的書頁數要多一些一樣。2 索引減慢了資料的插入和刪除速度。因為每次刪除更新資料都要更新索引,乙個表擁有的索引越多則寫操作的平均效能下降越大。cre...

索引和約束的刪除

建立主建約束和唯一約束時會自動建立同名索引。相關資料字典 user constraints,user indexes 使用下面命令刪除索引索引時,會提示錯誤。drop index table pk 這是可以刪除約束再刪除索引。alter table table drop constraint tab...