嗨,我有这两个表:用户和朋友(friend_status = 1 表示请求已发送,friend_status = 2 表示他们是朋友)。现在我想选择所有用户不是特定用户的朋友。怎么做?
假设当前用户是 1。我试过这个 SQL。它有效,但它太长而且太慢。第一个选择向 user1 发送请求但未被接受的所有用户。第二个选择从 user1 接收请求的所有用户。第三个和第四个选择所有不在“朋友”表中的用户。
SELECT user_id, name, email
FROM
(
SELECT user_id, name, email
FROM users u INNER JOIN friends f ON u.user_id = f.sender
WHERE f.receiver = 1 AND friend_status <> 2
UNION
SELECT user_id, name, email
FROM users u INNER JOIN friends f ON u.user_id = f.receiver
WHERE f.sender = 1 AND friend_status <> 2
UNION
SELECT u.user_id, u.name, u.email
FROM users u LEFT JOIN friends f ON u.user_id = f.sender
WHERE f.receiver IS NULL
GROUP BY user_id
UNION
SELECT u.user_id, u.name, u.email
FROM users u LEFT JOIN friends f ON u.user_id = f.receiver
WHERE f.sender IS NULL
GROUP BY user_id
) T
GROUP BY user_id
更新:添加图片。