表:
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
并将其回声输出:SELECT Count(laterecords.studentid) AS late_count FROM laterecords
但我想也许有更好的解决办法?
最佳答案
简单的解决方法是在子查询中添加一个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