一尘不染

SQL查询-子查询返回多个行

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和回显它:

SELECT Count(laterecords.studentid) AS late_count FROM laterecords

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


阅读 148

收藏
2021-03-08

共1个答案

一尘不染

简单的解决方法是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
2021-03-08