我有很多表代表可以“参与”的小组(比如俱乐部,社团和班级),以及代表所有“参与”(参与)的表格。因此,我可以找出用户参与的课程如下:
SELECT * FROM Participations WHERE user_id = 1 and Participations.group_type = "Class";
我还可以通过这样的方式找出哪个用户在俱乐部中的ID为12:
SELECT * FROM Users INNER JOIN Participations ON (Users.id = Participations.user_id) WHERE Participations.group_type = "Club" and Participations.group_id = 12;
我想找到所有在Club 12,Club 20或Class 10中的用户,而不返回任何未参与任何这些组的用户。
SELECT * FROM Users INNER JOIN Participations ON (Users.id = Participations.user_id) WHERE (Participations.group_type = "Club" AND Participations.group_id IS IN (12,20)) OR (Participations.group_type = "Class" AND Participations.group_id IS 10)
此外,我想显示他们参与的群组的名称,同样不包括任何未参与任何这些群组的用户(如下所示):
SELECT Users.*, Classes.name, Clubs.name, FROM Users, Classes, Clubs, Participations (Users.id = Participations.user_id) WHERE Users.id = Participations.user_id AND ((Participations.group_type = "Club" AND Participations.group_id IS IN (12,20)) OR (Participations.group_type = "Class" AND Participations.group_id IS 10))
但我更喜欢使用显式连接。它可行吗?
答案 0 :(得分:2)
您只需向join子句添加所需条件:
SELECT * FROM Users
INNER JOIN Participations
ON (Users.id = Participations.user_id)
AND ( (Participations.group_type = "Club" AND Participations.group_id IS IN (12,20))
OR (Participations.group_type = "Class" AND Participations.group_id IS 10) )