1. 程式人生 > >mysql 中in和exists的區別

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 查詢了一次