2016-09-13 27 views
0

遇到下列问题就来了:关系司:我整除

编写一个查询,找到完全相同的朋友,另一个用户的所有用户U.

下面是表(和一个SQL小提琴:http://sqlfiddle.com/#!9/457260/1):

  • 用户:
    • USER_ID:诠释
  • 友谊:
    • USER_ID:诠释
    • friend_id:诠释

,我有我的查询的问题是,它返回有用户相同的朋友或超过用户U.

SELECT * 
FROM users INNER JOIN friendships ON users.id = friendships.user_id 
WHERE users.id != 1 AND friendships.friend_id IN (
    SELECT DISTINCT friendships.friend_id 
    FROM friendships 
    WHERE friendships.user_id = 1 
) 
GROUP BY users.id 
HAVING COUNT(DISTINCT friendships.friend_id) = (
    SELECT COUNT(DISTINCT friendships.friend_id) 
    FROM friendships 
    WHERE friendships.user_id = 1 
); 

回答

1

最简单的方法是聚集朋友,然后做比较:

with f as (
     select user_id, array_agg(friend_id order by friend_id) as friends 
     from friendships f 
     group by user_id 
    ) 
select user_id 
from f 
where f.friends = (select friends from f where user_id = 1) and 
     f.user_id <> 1; 
+0

你可能想使用'ARRAY_AGG()'这里。 – Patrick

+0

帕特里克是对的,我也加了'AND f.user_id!= 1'来确保它不会返回同一个用户。 :d –