2012-05-04 60 views
3

表:SQL查詢 - 子查詢返回不止一行

laterecords 
----------- 
studentid - varchar 
latetime - datetime 
reason - varchar 

我的查詢:

SELECT laterecords.studentid, 
laterecords.latetime, 
laterecords.reason, 
(SELECT Count(laterecords.studentid) FROM laterecords 
     GROUP BY laterecords.studentid) AS late_count 
FROM laterecords 

我得到 「MySQL的子查詢返回多行」 的錯誤。

我知道這個查詢使用下面的查詢解決方法:

SELECT laterecords.studentid, 
laterecords.latetime, 
laterecords.reason 
FROM laterecords 

然後使用PHP循環,雖然結果並做以下查詢來獲取late_count和echo出來:

SELECT Count(laterecords.studentid) AS late_count FROM laterecords 

但我認爲可能有更好的解決方案?

回答

3

簡單的解決方法是在你的子查詢中添加WHERE條款:

SELECT 
    studentid, 
    latetime, 
    reason, 
    (SELECT COUNT(*) 
    FROM laterecords AS B 
    WHERE A.studentid = B.student.id) AS late_count 
FROM laterecords AS A 

一個更好的選擇(在性能方面)是使用加入:

SELECT 
    A.studentid, 
    A.latetime, 
    A.reason, 
    B.total 
FROM laterecords AS A 
JOIN 
(
    SELECT studentid, COUNT(*) AS total 
    FROM laterecords 
    GROUP BY studentid 
) AS B 
ON A.studentid = B.studentid