【问题标题】:Get all none contact from a user sql从用户 sql 获取所有无联系人
【发布时间】:2021-05-02 11:29:34
【问题描述】:

希望你一切都好:)。

我在 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)
                 );

【问题讨论】:

  • 编辑您的问题并将示例数据和所需结果显示为文本而不是不可读的图像。

标签: mysql sql mariadb


【解决方案1】:

如果您想要没有互惠关系的记录(正如您的描述所暗示的那样),您可以使用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
                 );

【讨论】:

  • 是的,唯一的问题是我已经使用了一个不存在的。我想从没有互惠关系的用户表中获取所有用户。但是这个 sql 语句不是我搜索的(它只显示联系人表中没有互惠
  • @Forcela8 。 . .只需在外部查询中使用连接即可。
猜你喜欢
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
相关资源
最近更新 更多