2011-09-10 210 views
1

我已經執行的子查詢和連接兩個表,然後將其與一個主表加入以下SQL查詢:高效SQL查詢連接

SELECT a.id, cgso.sf_guard_user_id as cgso, cgal.sf_guard_user_id as cgal 
FROM table_a a 
JOIN ( SELECT cgso.sf_guard_user_id, cgso.speciality_id 
     FROM table_c g 
     JOIN table_b as cgso 
      ON g.user_id = cgso.sf_guard_user_id and g.group_id = 2) as cgso 
    ON a.speciality_id = cgso.speciality_id 
JOIN ( SELECT cgal.sf_guard_user_id, cgal.speciality_id 
     FROM table_c g 
     JOIN table_b as cgal 
      ON g.user_id = cgal.sf_guard_user_id and g.group_id = 1) as cgal 
    ON a.speciality_id = cgal.speciality_id 

查詢的輸出是:

id | cgso | cgal 
---------------- 
1 | 2 | 54 

輸出是否正常,但是是否有更高效的方法來獲得相同的輸出?任何提示或建議將不勝感激。

謝謝

+0

這也許應該問的[代碼審查(http://codereview.stackexchange.com/)如果可能的話,這是一個關於改善已經工作的代碼的問題網站。 StackOverflow更多的是解決代碼問題。 –

回答

2

你應該能夠只是簡化加入...

SELECT a.id, cgso.sf_guard_user_id as cgso, cgal.sf_guard_user_id as cgal 
FROM table_a a 
INNER JOIN table_c g2 ON g1.group_id = 2 
INNER JOIN table_b cgso ON g2.user_id = cgso.sf_guard_user_id AND cgso.specialty_id = a.specialty_id 
INNER JOIN table_c g1 ON g1.user_id = 1 
INNER JOIN table_b cgal ON g1.user_id = cgal.sf_guard_user_id AND cgal.specialty_id = a.specialty_id 
+0

非常感謝道格。 –