mysql之抛弃exists

2020-09-21  本文已影响0人  刘振宁的博客

sql中一对多的表结构,要根据多的一方进行查询,返回一的那方的数据,这时候需要用到exists,比如:

create table class {
    long id,
    varchar(20) name
}

create table teacher {
    long id,
    varchar(20) name,
    long class_id
}

一个班级有多个老师,查询有叫"张三"老师的班级信息,下面是不用exists的简单处理方式。

select c.* from class c left join teacher t on c.id = t.class_id
where t.name = '张三'

问题在哪里:假如A班有两个老师都叫张三,则会搜出两个A班来,而A班只有一个班级,假如前台页面有分页的话,会出现问题.
用exists来实现查询一个班级:

select * from class c 
where exists(select 1 from teacher t where t.class_id = c.id and t.name = '张三')

这时候,只会搜出一个班级来,问题是:<u>exists不会走索引,会造成全部扫描,假如表格数据量大的话,会造成查询慢的问题</u>

解决方案

  1. 用group by 代替exists
select c.* from class c left join teacher t on c.id = t.class_id
where t.name = '张三' group by c.id
  1. 分成子查询来处理
select * from class c 
where c.id in (select class_id from teacher t where t.name = '张三')

这样既可以用上索引,又可以解决分页问题.

上一篇下一篇

猜你喜欢

热点阅读