2014-02-07 91 views
0

我有兩個MySQL表:MySQL變更多個查詢到單個查詢

tblcoach:包含字段(coachid,coachschoolid,otherstuff)

tblschool:包含字段(schoolid,schooldivision)

我試圖獲得僅限於與教練處於同一學校的那些學校的學校名單。

這段代碼我有工作,但有沒有辦法產生一個單一的MySQL查詢來實現相同的結果?

SELECT @cs := coachschoolid FROM tblcoach c; 
SELECT @sd := s.schooldivision FROM tblschool s WHERE s.schoolid = @cs; 
SELECT s2.schoolid, s2.schoolname FROM tblschool s2 WHERE schooldivision = @sd 
+1

爲什麼不使用嵌套查詢?用查詢本身替換你的變量,它變成一個查詢。 –

回答

0

巢查詢:

select schoolId, schoolname 
from tblschool 
where 
    schooldivision = (
     select schooldivision from tblschool where schoolid = (
      select coachschoolid from tblcoach 
     ) 
    ) 
0

這似乎將有1名教練工作。 您可以使用自聯接來做到這一點:

SELECT s2.schoolid, s2.schoolname 
FROM tblschool s 
INNER JOIN tblschool s2 on s.schooldivision = s2.schooldivision 
WHERE s.schoolid = ? 

允許您在schoolID通過。如果你想通過coachID:

SELECT s2.schoolid, s2.schoolname 
FROM tblschool s 
INNER JOIN tblschool s2 on s.schooldivision = s2.schooldivision 
INNER JOIN tblcoach c on c.coachschoolid = s.schoolid 
WHERE c.coachid = ?