mysql 中in和exists的区别

有两张表:student 和 studentcource
student student 表
这里写图片描述 studentcource 表

需求:查询所有成绩小宇60分的同学

  • in 原理:

1、先查询 <60 学生得到student_id列表

select student_id from studentcource where score<60;

2.在列表中取值

select * from student where id in 列表 ;

  • exists 原理:

1、查询 <60分 选课表信息

select * from studentcource where score<60;

2、子查询与主查询发生关系

select * from student where exists (select * from studentcource where score<60 and student.id = studentcource.student_id );

结论:exists 效率好于 in,因为in是进行了两次查询,exists 查询了一次

猜你喜欢

转载自blog.csdn.net/eaphyy/article/details/79448928
今日推荐