MySQL之跨表查询与索引

720 阅读1分钟

这是我参与11月更文挑战的第2天,活动详情查看:2021最后一次更文挑战

一、笛卡尔积连接

在演示笛卡尔积连接之前,我们先看看相关表的结构:

  • article表

image.png

  • article_cate表

image.png

笛卡尔积连接就是实现跨表查询的一种方式。

select article.id as id,article.title as title,article.state as state,article_cate.title as cate from article,article_cate where article.cate_id=article_cate.id

二、内连接

项目中使用比较多的是内连接来进行跨表查询。内连接主要是加入了INNER JOIN和ON两个关键字。

select article.id as id,article.title as title,article.state as state,article_cate.title as cate from article INNER JOIN article_cate on article.cate_id = article_cate.id; 

其他方法:使用IN来进行查询,例如:张三选修的课程id对应的课程名称是什么,我们首先看下数据表的结构:

  • lesson表

image.png

  • student表

image.png

  • lesson_student表

image.png

查询张三选修的课程的名称

select * from lesson where id in (select lessonId from lesson_student where studentId=1);

查询哪些学生选修了Java程序设计

select * from student where id in (select studentId from lesson_student where lessonId=2);

三、MySQL索引

当查询海量数据的时候,通过索引可以增加查询的效率,极大的降低查找的时间。

  1. 创建索引

给name创建索引名为index_name。

create index index_name on student(name);  
  1. 查看索引
show index from student;
  1. 删除索引
drop index index_name on student;
  1. 创建唯一索引
create unique index index_name on student(name);

我们也可以通Navicat等可视化工具来设置索引,通过右键选择某个数据表,选择设计表,然后添加索引。

image.png