溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

數(shù)據(jù)庫中主鍵,外鍵與索引的示例分析

發(fā)布時間:2022-01-15 14:25:09 來源:億速云 閱讀:196 作者:小新 欄目:編程語言

這篇文章主要介紹了數(shù)據(jù)庫中主鍵,外鍵與索引的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

create table class(id int not null primary key,name char(16));設(shè)置id為主鍵

create table student2(id int(11) not null,name char(16) not null,class_id int(11) not null,primary key(id),key fk_class_key(class_id),
contraint fk_class_key foreign key (class_id) references class(id));設(shè)置id 為主鍵,設(shè)置class_id為fk_class_key外鍵類型,限定外鍵類型 外鍵值為class_id
并與class表的id關(guān)聯(lián)

insert into student2(id,name,class_id) values(1,'alex', 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`testdb`.`student2`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`))
此時如果class 表中不存在id 1,student表也插入不了,這就叫外鍵約束

insert into class(id,name) values(1,"linux");
insert into student2(id,name,class_id) values(1,'alex', 1);

如果有student表中跟這個class表有關(guān)聯(lián)的數(shù)據(jù),你是不能刪除class表中與其關(guān)聯(lián)的紀錄的
delete from class where id =1;
ERROR1451(23000): Cannot delete or update a parent row: a foreign key constraint fails (`testdb`.`student2`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`))


有四種方式來添加數(shù)據(jù)表的索引:
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): 該語句添加一個主鍵,這意味著索引值必須是唯一的,且不能為NULL。
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): 這條語句創(chuàng)建索引的值必須是唯一的(除了NULL外,NULL可能會出現(xiàn)多次)。
ALTER TABLE tbl_name ADD INDEX index_name (column_list): 添加普通索引,索引值可出現(xiàn)多次。
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list):該語句指定了索引為 FULLTEXT ,用于全文索引。
drop index index_name on tbl_name;刪除索引
alter table tbl_name drop index index_name;刪除索引
tbl_name:表名
index_name:索引名
column_list:列名

SHOW INDEX FROM table_name\G
show keys from tbl_name;查看索引

alter table tbl_name add priamry key(column_list);添加主鍵 主鍵也是索引功能
alter table tbl_name drop primary key;刪除主鍵

感謝你能夠認真閱讀完這篇文章,希望小編分享的“數(shù)據(jù)庫中主鍵,外鍵與索引的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI