【问题标题】:Relational Division: Exact Division关系除法:精确除法
【发布时间】:2016-09-13 02:56:01
【问题描述】:

我遇到了以下问题:

编写查询以查找与另一个用户 U 有完全相同朋友的任何用户。

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

  • 用户:
    • user_id: Int
  • 友谊:
    • user_id: Int
    • 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
);

【问题讨论】:

    标签: sql postgresql activerecord relational-division


    【解决方案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;
    

    【讨论】:

    • 你可能想在这里使用array_agg()
    • Patrick 是对的,我还添加了AND f.user_id != 1 以确保它不会返回相同的用户。 :D
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多