0

我有三个(我继承了它们)表,一个用户表,一个课程表和一个测试表,我需要从中测量用户的活动。例如,以下查询将为我提供其中一组中的用户数 -

SELECT COUNT(Users.ID), `CourseSessions`.`CourseID`
FROM `Users`
LEFT OUTER JOIN `CourseSessions`
ON `Users`.`ID` = `CourseSessions`.`UserID`
WHERE `Users`.`CredentialID` IN (2, 3)
AND `CourseSessions`.`CourseID` IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
AND `CourseSessions`.`TimeIn` BETWEEN '2012-06-01' AND '2012-12-31'
GROUP BY `CourseSessions`.`CourseID`;

结果是这样的 -

COUNT, CourseID 
32     1
43     2 
31     3
49     4
36     5
21     6
5      7
2      15

我可以将 CourseSessions 更改为 TestResults 以获得另一组数字。当有人只是参加课程或参加考试时,问题就出现了。

我需要做的是计算一次用户,如果他们存在于一个或两个表中。鉴于以下 -

User     Course.courseID     Test.courseID
A              1
B              1                  1
C                                 1

courseID 1 的计数应为 3。

我已经看了几个小时,并认为也许我应该做一个 SUM...IF 但这并没有按预期工作。我已经尝试过子选择,但我最终得到了太多的列。总而言之,我已经很好地缠绕在这个轴上。

当两个表中的用户存在一条数据时,如何获得单个计数?

4

1 回答 1

2

这应该给你你正在寻找的东西:

SELECT COUNT(CoursesTest.UserID), CourseID
FROM (
    SELECT UserID, CourseID
    FROM CourseSessions
    WHERE TimeIn BETWEEN '2012-06-01' AND '2012-12-31'
    -- extra filters on CourseSessions here
    UNION

    SELECT UserID, CourseID
    FROM TestResults
    -- extra filters on TestResults here
) AS CoursesTest
JOIN Users ON Users.ID = CoursesTest.UserID
WHERE
    Users.CredentialID IN (2, 3)
    AND CoursesTest.CourseID IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
GROUP BY CourseID

CourseID我认为如果您之前进行过滤,即在子查询中,查询会更快一些。这意味着复制IN条件,但我认为 MySQL 不够聪明,无法优化查询。

SELECT COUNT(CoursesTest.UserID), CourseID
FROM (
    SELECT UserID, CourseID
    FROM CourseSessions
    WHERE TimeIn BETWEEN '2012-06-01' AND '2012-12-31'
    AND CourseID IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
    -- extra filters on CourseSessions here

    UNION

    SELECT UserID, CourseID
    FROM TestResults
    WHERE CourseID IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
    -- extra filters on TestResults here

) AS CoursesTest
JOIN Users ON Users.ID = CoursesTest.UserID
WHERE Users.CredentialD IN (2, 3)
GROUP BY CourseID
于 2013-02-13T19:16:12.270 回答