朋友关系查询

时间:2009-10-17 17:29:20

标签: sql mysql

我有以下表格:

USERS

  • ID
  • 用户名
  • 电子邮件
  • 密码
  • 状态

FRIENDS

  • ID
  • USER_ID
  • friend_id
  • 创建

要查找用户朋友,我使用:

SELECT f.friend_id, 
       u.username
  FROM friends f
  JOIN friends m ON m.user_id = f.friend_id 
                AND m.friend_id = f.user_id
  JOIN users u ON u.user_id = f.friend_id
 WHERE f.user_id = 1234

......效果很好。

ISSUE

我无法用其他方式找出类似的查询,但找到所有不是朋友的用户。它必须是一样的东西,让所有的朋友,获得所有的用户,删除所有朋友离开剩余的用户?

1 个答案:

答案 0 :(得分:5)

    SELECT u1.username, u2.username AS not_friend
      FROM users u1
      JOIN users u2 on u1.user_id != u2.user_id
 LEFT JOIN friends f1 on u1.user_id = f1.user_id
                     and u2.user_id = f1.friend_id
 LEFT JOIN friends f2 on u2.user_id = f2.user_id 
                     and u1.user_id = f2.friend_id
     WHERE u1.user_id = 1234
       AND (f1.user_id IS NULL OR f2.user_id IS NULL)

给朋友们:

SELECT u1.username, u2.username AS friend
  FROM users u1
  JOIN users u2 on u1.user_id != u2.user_id
  JOIN friends f1 on u1.user_id = f1.user_id
                 and u2.user_id = f1.friend_id
  JOIN friends f2 on u2.user_id = f2.user_id 
                 and u1.user_id = f2.friend_id
 WHERE u1.user_id = 1234