开发者

How can I join multiple polymorphic tables without pulling back blank records?

I have many tables that represent groups that can be "participated" in (let's say Clubs, Societies, and Classes), and a table representing all "participations" (Participations). Therefore, I can find out what classes a user is participating in as follows:

SELECT * FROM Participations WHERE user_id = 1 and Participations.group_type = "Class";

I could also find out which users are in the club with the id 12 by doing something like this:

SELECT * FROM Users INNER JOIN Participations ON (Users.id = Participations.user_id) WHERE Participations.group_type = "Club" and Participations.group_id = 12;

I WANT to find all of the users who are in Club 12, or Club 20, or Class 10, without returning any users who are not participating in any of these groups.

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)

And furthermore, I want to display the name of the group they participated in, again without including any users who are not participating in any of these groups (something like this):

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 =开发者_StackOverflow社区 "Club" AND Participations.group_id IS IN (12,20)) OR (Participations.group_type = "Class" AND Participations.group_id IS 10))

But I would prefer to use explicit joins. Is it doable?


You can just add required conditions to the join clause:

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) )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜