我有一个学校学生列表的 SELECT 语句,它目前使用以下代码运行,但是我发现每次计数需要 1-2 秒,这个数据库上的大多数其他简单查询不到半秒所以我认为我在这里做得非常低效。有一个更好的方法吗?1-2 秒可能听起来不多,但在更详细的声明中,我在下面添加了还计算存在/不存在的主题等,因此当我将所有内容包含在声明中时,运行时间接近 30 秒。
SELECT studentID AS sID, stu.name AS Name,
(
SELECT COUNT( * )
FROM attendance
WHERE ((sID = 1)
AND classdate < CURDATE( ))
) AS present,
(
SELECT COUNT( * )
FROM attendance
WHERE ((sID != 1)
AND classdate < CURDATE( ))
) AS absent
FROM attendance
INNER JOIN students AS stu ON attendance.studentID = stu.id
WHERE awayid != -1
GROUP BY sID
ORDER BY present ASC
---------------------------------------------
| sID | Name | present | absent |
| 1 | John | 28 | 2 |
| 2 | Richard | 26 | 4 |
| 3 | Harry | 22 | 8 |
| 4 | Sarah | 22 | 8 |
| 5 | Tanya | 20 | 10 |
| 6 | Nathan | 20 | 10 |
| 7 | Kate | 20 | 10 |
---------------------------------------------