温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

数据库中主键,外键与索引的示例分析

发布时间:2022-01-15 14:25:09 来源:亿速云 阅读:179 作者:小新 栏目:编程语言

这篇文章主要介绍了数据库中主键,外键与索引的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

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;删除主键

感谢你能够认真阅读完这篇文章,希望小编分享的“数据库中主键,外键与索引的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI