gpt4 book ai didi

具有不同计数的 mySQL 多连接

转载 作者:行者123 更新时间:2023-11-29 00:01:43 25 4
gpt4 key购买 nike

我正在尝试查询 3 个表:

教室:

id |    name  
----------------
1 | bob's class

student_enrollment:

studentId | classroomId  
-----------------------
1 | 1

student_progress:

studentId | dateTime 
---------------------
1 | 2014-08-15 09:33:23

我试图以这样的结果结束:

classroomName | studentId | days
------------------------------------------
Bob's class | 1 | 112

days 是特定学生有 dateTime 条目的不同天数。

SELECT classroom.name, student_enrollment.studentId, student_progress.dateTime   
FROM classroom
JOIN student_enrollment ON student_enrollment.classroomId = classroom.id
JOIN student_progress ON student_progress.studentId = student_enrollment.studentId
WHERE `dateTime` >= '2014-08-01 09:00:34'
ORDER BY classroom.name

给我一​​张表格,其中包含每个学生的每个 dateTime 条目。我尝试向查询添加计数的任何方式最多只能得到一个只有一名学生和不同 dateTime 天的总计数的结果。

SELECT classroom.name, student_enrollment.studentId, COUNT(DISTINCT YEAR(student_progress.dateTime),MONTH(student_progress.dateTime),DAY(student_progress.dateTime)) AS days 
FROM classroom
JOIN student_enrollment ON student_enrollment.classroomId = classroom.id
JOIN student_progress ON student_progress.studentId = student_enrollment.studentId
WHERE `dateTime` >= '2014-08-01 09:00:34'
ORDER BY classroom.name

我已经尝试将计数移动到连接部分的子查询,以及其他各种操作,但最终会出现诸如 unknown table student_progress 之类的错误,而且无法成功似乎找到了将查询放在一起以获得每个 studentIddateTime 条目的不同计数的正确方法。

最佳答案

您似乎想要计算不同的日期。尝试,而不是:

SELECT classroom.NAME,
student_enrollment.studentId,
COUNT(DISTINCT DATE(student_progress.DATETIME)) AS days
FROM classroom
INNER JOIN student_enrollment
ON student_enrollment.classroomId = classroom.id
INNER JOIN student_progress
ON student_progress.studentId = student_enrollment.studentId
WHERE `dateTime` >= '2014-08-01 09:00:34'
GROUP BY classroom.NAME, student_enrollment.studentId,
ORDER BY classroom.NAME

我也在此处添加了明确的 GROUP BY,只是因为无论何时您在顶部使用公式进行聚合,您都应该对其他字段进行 GROUP BY。 MySQL 无论如何都会这样做,但最好是明确的,这样你就不会得到奇怪的结果。

关于具有不同计数的 mySQL 多连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477926/

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