2014-04-07 44 views
2

我的表是這樣的:的MySQL:查詢設計問題

表1(學生)
Table 1

表2(結果)

Table 2

我想選擇表1中的所有學生students誰有4結果在results表。我嘗試此查詢,但沒有成功:

SELECT * 
FROM students 
WHERE gender = 'm' 
AND (SELECT COUNT(result) AS count 
FROM results 
INNER JOIN students ON results.stuID = students.stuID 
WHERE result !=0 
) =4 
ORDER BY rank ASC 

回答

0

你必須使用alias爲表還 -

SELECT * 
FROM students as a 
WHERE gender = 'm' 
AND (SELECT COUNT(result) AS count 
FROM results as b 
WHERE b.stuID = a.stuID AND 
(result!=0 OR result IS NOT NULL OR result!='') 
) = 4 
ORDER BY rank ASC 
+0

工作完美!謝謝,我會盡快接受你的回答。 – iCode

1

嗯,這是一個有點令人費解。 where子句應該在子查詢之後,並且子查詢仍然需要連接回主查詢。

SELECT * FROM students 
INNER JOIN (SELECT COUNT(result),results.stuID as count FROM results WHERE result != 0) as result_count 
ON result_count.stuID = students.stuID 
WHERE result_count.count =4 AND students.gender = 'm' 
ORDER BY rank ASC 
4

您可以通過加入和HAVING子句來檢查每個學生組的計數重寫查詢,這樣可以在不使用有時會影響性能的子查詢進行

SELECT s.*,COUNT(*) AS count 
FROM students s 
INNER JOIN results r ON r.stuID = s.stuID 
WHERE r.result !=0 
GROUP BY s.stuID 
HAVING count =4 
ORDER BY s.rank ASC 
+2

就優化查詢而言,它是最好的+1 –