gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:21:00 26 4
gpt4 key购买 nike

表:

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

关于php - SQL 查询 - 子查询返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com