MySQL基础课连载3-等值连接也叫内连接 索引 外键

一.等值连接也叫内连接:

1.通过inner join连接了score1和info1两个表读取了score1中的字段id和name和info1表中对应的phone字段

select score1.id,score.name,info1.phone from score inner join info on score1.name=info1.name;

2.left join:读取score1的所有数据即使表info1中没有对应数据:


select score1.id,score1.name,info1.phone from score left join info on score1.name=info1.name;

3.right join与left join相反:

select score.id,score.name,info.phone from score right join info on score.name=info.name;

二.索引

1.添加索引,也可以创建表的时候直接添加:

create index ind_score1 on score1(name);

2.查看当前表中索引:

show index from score1;

3.删除索引:

drop index ind_score1 on score1;

4.alter命令创建索引:

alter table score1 add index ind_score1(name);

5.alter命令删除索引:

alter table score1 drop index ind_score1;

6.创建唯一索引,与普通索引区别就是唯一索引值必须唯一,但可以为空,索引用于快速找到所需数据:

create unique index 索引名 on 表名(字段名);

三.外键:

1.如果一个表某个字段指向另一个表的主键,就称之为外键,被指向的表称之为主表也叫父表,另一个表为从表也叫子表:

create table article_table(

article_id int(4) not null primary key auto_increment,

article_title char(20) not null,

author_id int(4) not null,

foreign key(author_id) references author_table(author_id));"

2.show create table article_table;通过这个命令我们可以看到表中存在的外键,下图

3.删除外键约束:

alter table 表名 drop foreign key 外键名

4外键:还可以通过外键给两表设置级联操作

on delete cascade

on update cascade

cascade表示关联操作,即如果父表中数据被删除或更新,子表中对应数据也会执行同样的操作

还有两个

set null表示子表数据不指向父表任何记录

restrict表示拒绝主表的相关操作,当不加这两句话时,默认就是restrict"

alter table article_table

-> add foreign key fk_id(author_id)

-> references author_table(author_id)

-> on delete cascade

-> on update cascade;

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容