不是朋友在mysql中查询

时间:2014-11-17 10:53:19

标签: mysql

我将下表users(id,username)和朋友表格设为friends(id,friend_one,friend_two,status)

假设我使用id为1的用户1登录我想要获取用户1上不是朋友的记录以及用户1已向其发送了朋友请求的记录。我怎样才能做到这一点。 status = 1表示两个用户都是朋友,status = 0表示好友请求待处理。

users(1,'A') 
users(2,'B')
users(3,'C')
users(4,'D')
users(5,'E')

好友表条目

friends(1,2,1)
friends(1,3,1)
friends(1,5,0)

预期结果

username ID status

D            4  
E       5    0    

2 个答案:

答案 0 :(得分:0)

未经测试:

SELECT users.username, friends.status 
FROM users LEFT JOIN friends on users.id = friends.fried_one 
WHERE users.id NOT IN (
    SELECT friends.friend_two WHERE friend_one = users.id AND status = 1
)

答案 1 :(得分:0)

尝试计算您的示例数据。我无法看到用户D的来源。

记录您的要求(仅限已经发送好友请求但未被接受的用户,因此状态为0): -

SELECT u2.username, u2.id, f.status
FROM users u1
INNER JOIN friends f
ON u1.id = f.friend_one
INNER JOIN users u2
ON f.friend_two = u2.id
WHERE u1.id = 1
AND f.status = 0

修改

修订后的查询还包括未向其发送好友请求的人: -

SELECT u2.username, u2.id, f.status
FROM users u1
INNER JOIN users u2
ON u1.id != u2.id
LEFT OUTER JOIN friends f
ON u1.id = f.friend_one
AND u2.id = f.friend_two
WHERE u1.id = 1
AND (f.status IS NULL
OR f.status = 0)

编辑 - 如果您想以两种方式检查朋友请求,请进一步修改查询: -

SELECT u2.username, u2.id, f.status
FROM users u1
INNER JOIN users u2
ON u1.id != u2.id
LEFT OUTER JOIN friends f
ON (u1.id = f.friend_one
AND u2.id = f.friend_two)
OR (u1.id = f.friend_two
AND u2.id = f.friend_one)
WHERE u1.id = 1
AND (f.status IS NULL
OR f.status = 0)