mysql - 从用户 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)
);
解决方案
如果您想要没有互惠关系的记录(正如您的描述所暗示的那样),您可以使用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
);
推荐阅读
- groovy - Jmeter groovy在Json中返回一组ID
- javascript - 使用 Fetch API 的 javascript HTTP GET 返回 401 Unauthorized 但在 Postman 中有效
- java - 从不同长度的用户字符串中读取到数组中
- oop - 状态机、封装和 OOP 设计
- javascript - ExceptionsManager.js:84 未处理的 JS 异常:ReferenceError:未定义响应
- postgresql - 如何在 PostgreSQL 中跳过 psql \COPY 中的空行
- sql - 将数据从列转换为行,仅当列的并集不为空时才选择,使用 where 子句检查不为空和 != ''
- node.js - 如何将 nodemon 用于 eslint 和 babel
- python-3.x - 将图像放在另一个图像之上的更有效方法 - OpenCV Python3
- asp.net-core - ASP.NET Core 静态文件返回为 Base64 编码