每行连接列的出现次数

时间:2019-01-16 20:10:55

标签: sql sqlite

我有一张包含课程的表。

create table Courses
(
  CourseId INTEGER
    primary key
  ...
);

通过M2M链接表...

create table User_Course_Links
(
  UserId INTEGER not null
    references Users,
  CourseId INTEGER not null
    references Courses,
  unique (UserId, CourseId)
);

...我已将其连接到包含Users的表。

create table Users
(
  UserId INTEGER
    primary key
  ...
);

现在,我想列出所有课程,以及有多少用户连接到每个课程。我该怎么办?

+----------+-----------+
| CourseId | UserCount |
+----------+-----------+
| Course 1 |        20 |
| Course 2 |         5 |
| Course 3 |        12 |
| ...      |       ... |

1 个答案:

答案 0 :(得分:0)

好,我找到了。可以使用以下查询:

SELECT Courses.CourseId, Count(Users.UserId) AS UserCount FROM Users
INNER JOIN User_Course_Links UCL on Users.UserId = UCL.UserId
INNER JOIN Courses Courses on UCL.CourseId = Courses.CourseId
GROUP BY Courses.CourseId

这将导致

+----------+-----------+
| CourseId | UserCount |
+----------+-----------+
| Course 1 |        20 |
| Course 2 |         5 |
| Course 3 |        12 |
| ...      |       ... |

或者,可以使用此查询:

SELECT Courses.CourseId, Count(Users.UserId) AS UserCount FROM Courses
LEFT OUTER JOIN User_Course_Links UCL on Courses.CourseId = UCL.CourseId
LEFT OUTER JOIN Users on UCL.UserId = Users.UserId
GROUP BY Courses.CourseId

还包括零用户的课程