2013-05-20 67 views
0

我需要选择7A班学生的考试成绩,但需要查看另一张表(student_profile)来识别7A中的学生(由student_id标识)。 我不知道哪下面的方法会更快,假定索引为student_id数据在两个表中创建:关于SQL查询的问题

方法1:

select * from exam_results r 
where exists 
(select 1 
    from student_profile p 
    where p.student_id = r.student_id 
    and p.class = '7A') 

方法2:在提前

select * from exam_results 
where student_id in 
(select student_id 
    from student_profile 
    where class = '7A') 

谢谢,

乔纳森

+3

去'EXISTS'。 –

+1

在任何现代的sql引擎上,查询执行计划都是一样的。 – Jodrell

+0

JW的+1。 ** [请参考链接进一步澄清你的疑惑](http://stackoverflow.com/questions/5018284/mysql-in-queries-terribly-slow-with-subquery-but-fast-with-explicit-values) ** – Luv

回答

0

如果您比较这两个查询,然后与EXISTS一个更快。然而,对这些问题的正确(通常更快)的方法是JOIN

select r.student_id, r.other_columns 
from exam_results r 
inner join student_profiles s 
on r.student_id = s.student_id 
where s.class = '7A' 
+0

我会给你一个加入方法的+1,但是否存在是否更快取决于,正如Jodrell所说,有太多的因素需要一个通用的答案。 –

+0

数据库中查询的性能取决于许多参数(索引,统计信息,满足条件的记录数量等等)。尝试通过检查访问计划来优化查询是一种很好的做法。但在尝试之前,您需要从查询的一种形式开始。我认为开发人员会从联接查询开始,然后进行优化。 – nakosspy

+0

是的,我同意这一点。 –

2

简短的回答,没关系。查询引擎会将它们视为相同。

就我个人而言,我会考虑这种语法。

select 
      r.* 
    from 
      exam_results r 
     join 
      student_profile p 
       on p.student_id = r.student_id 
    where 
      p.class = '7A' 

如果省略,则暗示inner

由于现代查询引擎已经很完善,所以你会得到相同的性能,但是我认为这个标准语法更易于扩展和阅读。


如果将来扩展此查询,多个连接条件将比多个存在或插件更容易优化。