mySQL多连接具有不同的计数

时间:2015-04-06 19:10:10

标签: mysql

我正在尝试查询3个表:

classroom

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之类的错误,而且似乎无法看似以正确的方式登陆以将查询放在一起,以获得每个dateTime的{​​{1}}条目的独特计数。

2 个答案:

答案 0 :(得分:1)

看起来你想要的是计算不同的DATE。请尝试改为:

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无论如何都会这样做,但最好是明确的,这样你就不会得到奇怪的结果。

答案 1 :(得分:0)

我认为你想要这些内容:

SELECT
    classroom.name,
    student_progress.studentId,
    COUNT(DISTINCT DATE_FORMAT(student_progress.dateTime, '%y-%m-%d')) AS days
FROM classroom
JOIN student_enrollment ON
    student_enrollment.classroomId = classroom.id
JOIN student_progress ON
    student_progress.studentId = student_enrollment.studentId
GROUP BY
    classroom.name,
    student_progress.studentId;

这应该正确计算不同日期与dateTime的不同值。我不建议命名你的列dateTime顺便说一句,以后会导致混乱(对你或下一个开发者来说)。