主鍵,外鍵與索引

create table class(id int not null primary key,name char(16));設置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));設置id 爲主鍵,設置class_id爲fk_class_key外鍵類型,限定外鍵類型 外鍵值爲class_id
並與class表的id關聯

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表有關聯的數據,你是不能刪除class表中與其關聯的紀錄的
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`))


有四種方式來添加數據表的索引:
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): 該語句添加一個主鍵,這意味着索引值必須是唯一的,且不能爲NULL。
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): 這條語句創建索引的值必須是唯一的(除了NULL外,NULL可能會出現多次)。
ALTER TABLE tbl_name ADD INDEX index_name (column_list): 添加普通索引,索引值可出現多次。
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;刪除主鍵

參考:https://www.cnblogs.com/alex3714/articles/5950372.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章