因此,我们有games
表,其中有许多participants
。每个参与者都有一个user_id
列。现在,我们需要为特定的参与者找到游戏。
我的意思是拥有一组(1,2,3)
ID,我们需要找到一个参与者完全是三个用户的游戏。
我正在使用活动记录,并且尝试过类似的操作:
Game.joins(:participants).where("user_id in (?)", [1,2,3])
但是它返回具有至少一个给定用户的所有游戏。
答案 0 :(得分:0)
在SQL中,您可以使用group by
和having
:
select g.games_id
from games g
group by g.games_id
having count(*) = sum(case when user_id in (1, 2, 3) then 1 else 0 end) and
count(*) = 3; -- number of users in list
第一个条件检查参与者中是否只有所有指定的用户。第二个检查所有用户都包括在内。