首页 > 解决方案 > 从用户 sql 获取所有无联系人

问题描述

我希望你一切都好 :)。

我在 sql 中遇到了一个我无法解决的问题。我想让所有尚未与没有元组的用户成为朋友的人。

也就是说,在我的列user_id或contact_user_id中,如果:user_id = 1和contact_user_id = 2(他们是朋友),它不会向用户2显示它不是用户1的朋友。

它应该为用户 2 显示他缺少用户 3,4 而不是 1 也不是他自己

我目前有这样的请求,但它没有显示出良好的预期结果。

非常感谢愿意花时间回答的人

他们是没有第一行的期望结果(因为他们已经是朋友):

想要的结果

我暂时得到了这个sql语句:

select us.user_id, us.login 
from user us where u.user_id!=2 
and not exists (select 1 from contact ctc 
where ctc.contact_user_id = us.user_id 
and ctc.user_id = 2);

编辑:我可能创建了 sql 请求

select u.*
from user u
where not exists (select 1
                  from contact c
                  where (c.user_id = u.user_id and c.contact_user_id = 2) or (c.contact_user_id= u.user_id and c.user_id=2)
                 );

标签: mysqlsqlmariadb

解决方案


如果您想要没有互惠关系的记录(正如您的描述所暗示的那样),您可以使用not exists

select c.*
from contact c
where not exists (select 1
                  from contact c2
                  where c2.contact_user_id = c.user_id and
                        c.user_id = c.contact_user_id
                 );

如果您想从另一个表中获取更多信息,只需加入外部查询:

select c.*
from contact c join
     user u
     on c.user_id = u.user_id
where not exists (select 1
                  from contact c2
                  where c2.contact_user_id = c.user_id and
                        c.user_id = c.contact_user_id
                 );

推荐阅读