无论如何,如果没有我向您显示表格,您将能够帮助优化此查询?所有这些疑问都源于优化SQL查询与计数表的多个连接
我原来的表有以下几列和表名为laterec-学生
--------------------------------------------------------------
| studentid | name | class | latetime | waived |
--------------------------------------------------------------
| ID1111STU | Stu 1 | 1A |2012-01-09 08:09:00 |Waived |
SELECT A.class, NoStudentsLate, 1xLATE, 2xLATE FROM (
SELECT
class,
count(DISTINCT studentid) AS NoStudentsLate
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY class
) AS A
LEFT JOIN (
SELECT class, count(distinct studentid) AS 1xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=1) as temp
GROUP BY class
) AS B ON A.class=B.class
LEFT JOIN (
SELECT class, count(distinct studentid) AS 2xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=2) as temp
GROUP BY class
) AS C ON A.class=C.class
这就是我试图完成
---------------------------------------------------------------------
| Class | Total # of students late | # late 1 times | # late 2 times |
---------------------------------------------------------------------
| 1A | 5 | 3 | 2 |
| 1B | 3 | 3 | 0 |
---------------------------------------------------------------------
所以这是什么意思,在1A班,总共有5名学生迟到使用学生ID计算。在这5人中,3人迟到一次,2人迟到两次。
再次在1B班,共有3名学生迟到了,他们都只迟了一次。
如果你解释你的业务逻辑,这将有所帮助。 1xlate和2xlate应该是什么意思?就像你期待我们通过阅读你的代码来弄清楚你想做什么。这很难。谢谢。 –
好的,基本上这个表格包含了迟到的学生数量的数据。我编辑了上述 – d123
“迟到”是什么意思?我仍然无法说出你在这里做什么。 (请原谅我的挑剔,但我发现,当我真正理解我的查询应该产生什么时,更容易优化它。) –