2013-05-20 69 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

由於現代查詢引擎已經很完善,所以你會得到相同的性能,但是我認爲這個標準語法更易於擴展和閱讀。


如果將來擴展此查詢,多個連接條件將比多個存在或插件更容易優化。