主键与索引

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


猜你喜欢

转载自blog.51cto.com/13707996/2360620