3

桌子:

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 

但我认为可能有更好的解决方案?

4

1 回答 1

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
于 2012-05-04T08:19:43.790 回答