简体   繁体   English

MySQL获取尚未成为朋友的用户(自我排除)

[英]MySQL fetch users who are not yet friends (excluded self)

This is the continuation of my question here 这是我的问题的延续在这里

So basically, I want to fetch users who are not my friends. 因此,基本上,我想获取不是我朋友的用户。 However, if a user has just signed up and he has no friends yet, he should be able to see all users not his friends. 但是,如果用户刚刚注册并且还没有朋友,则他应该能够看到所有用户而不是他的朋友。

Please check my sql fiddle here 在这里检查我的sql小提琴

 Users 
 id    username   
 1     kyle
 2     jane
 3     jim
 4     carla

 Friends
 id    username  friend
 1     kyle      jane
 2     jane      kyle
 3     kyle      jim
 4     jim       kyle

When I query Kyle's not his friends: 当我询问凯尔不是他的朋友时:

SELECT * FROM users AS u 
                    WHERE u.username NOT IN 
                    (
                        SELECT f.username FROM friends as f
                        WHERE f.username = 'kyle'
                        OR f.friend = 'kyle'
                    )

It's displaying all users not his friends. 它显示的是所有用户,而不是他的朋友。 However, when I query Carla's, she is included in the result set. 但是,当我查询卡拉时,她就包含在结果集中。 She doesn't have friends yet but she shows up in the result set. 她还没有朋友,但是她出现在结果集中。 I want to remove (self) from the results and just display users not yet her friends. 我想从结果中删除(自己),只显示尚未显示其朋友的用户。

Any ideas? 有任何想法吗? I would gladly appreciate any help. 我很高兴得到任何帮助。 Thanks! 谢谢!

Your Friends table should relate IDs and not Names . 您的“ Friends表应关联IDs而不是Names

That said, here's the query that will return a list of all non-friends for every user: 就是说,这是将为每个用户返回所有非朋友列表的查询:

SELECT u1.username as `User`, GROUP_CONCAT(u2.username) as `Not friends with`
FROM Users u1
JOIN Users u2 ON u1.id <> u2.id 
LEFT JOIN Friends f ON u1.id = f.user AND u2.id = f.friend   
WHERE f.friend IS NULL
GROUP BY u1.id

SQL Fiddle SQL小提琴

The same for a single user ('jim'): 对于单个用户('jim')相同:

SELECT u1.username as `User`, GROUP_CONCAT(u2.username) as `Not friends with`
FROM Users u1
JOIN Users u2 ON u1.id <> u2.id 
LEFT JOIN Friends f ON u1.id = f.user AND u2.id = f.friend   
WHERE f.friend IS NULL
      AND u1.username = 'jim'

And Single-User Fiddle 单用户提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM