我遇到了Postgres的问题。这是一个例子: 我有3个表:用户,物品和盒子
盒子表:
user_id | item_id
1 | 3
1 | 4
1 | 6
1 | 7
2 | 5
2 | 10
2 | 11
3 | 5
3 | 6
3 | 7
鉴于此框表,我想在共享最小2的用户之间检索项目。因此预期的SQL查询结果应该是 item_id:6,7 因为用户1和用户3共享项目6和7。 但是用户2和3只共享一个项目:项目5因此项目5不在结果中。
我尝试了很多没有成功的方法。我想知道是否有人可以帮助我。
答案 0 :(得分:2)
试试这个。它返回6和7(如果你添加一个记录“1,5”,则返回5,6,7),但我没有对它进行过广泛的测试。
-- The Outer query gets all the item_ids matching the user_ids returned from the subquery
SELECT DISTINCT c.item_id FROM boxes c -- need DISTINCT because we get 1,3 and 3,1...
INNER JOIN boxes d ON c.item_id = d.item_id
INNER JOIN
--- the subquery gets all the combinations of user ids which have more than one shared item_id
(SELECT a.user_id as first_user,b.user_id as second_user FROM
boxes a
INNER JOIN boxes b ON a.item_id = b.item_id AND a.user_id <> b.user_id -- don't count items where the user_id is the same! Could just make the having clause be > 2 but this way is clearer
GROUP BY a.user_id,b.user_id
HAVING count(*) > 1) s
ON s.first_user = c.user_id AND s.second_user = d.user_id