关系除法:精确除法

Relational Division: Exact Division

我遇到了以下问题:

Write a query to find any users with exactly the same friends as another user U.

这是表格(和 SQL Fiddle: http://sqlfiddle.com/#!9/457260/1 ):

我的查询遇到的问题是 returns 用户拥有相同的朋友或多于用户 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
);

最简单的方法就是聚合好友,然后进行比较:

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;