2014-03-04 14 views
0

。我发现很难把它写成文字。我有一个名为conversation_users的表。它包含列:id,user_id,& conversation_id。将1个表格的结果与多个变量进行比较,发现提前感谢团结

我需要获取用户ID的列表,让我们说4 ...可以是9,并找到它们都有的共同的conversation_id,但不包含任何其他用户ID。

这可以在1个查询中完成吗?如果不是,有人可以指引我正确的方向吗?

谢谢!

回答

0

这是“set-set-set”查询的示例。你可以建,这为一组特定的用户为:

select cu.conversation_id 
from conversation_users cu 
group by cu.conversation_id 
having sum(cu.user = x) > 0 and 
     sum(cu.user = y) > 0 and 
     sum(cu.user = z) > 0 and 
     sum(cu.user not in (x, y, z)) = 0; 

having条款(除了最后一个)中的每一个条件检查一个给定的用户在交谈。最后检查没有其他用户在其中。

如果存储你所关心的在临时表或字符串的用户(在可怕的逗号分隔的格式),你仍然可以做到这一点:

select cu.conversation_id 
from conversation_users cu 
group by cu.conversation_id 
having count(distinct (case when find_in_set(cu.user, @USERLIST) > 0 then cu.user end)) = 
      1 + length(@USERLIST) - length(replace(@USERLIST, ',', '') and 
     count(distinct cu.user_id) = 1 + length(@USERLIST) - length(replace(@USERLIST, ',', '') 

它说的是匹配的数量列表中的用户等于列表的大小,并且匹配用户的总数是列表的大小。这两个条件表明列表中的所有成员都在谈话中。

+0

谢谢,这工作。对于laravel使用此链接作为参考:http://stackoverflow.com/questions/16976241/implementing-group-by-and-having-in-laravel-using-eloquent –

相关问题