mysql - 如何忽略表 1 中的记录(谁的 fk-refrence 必须存在于表 2 中)但条件不满足
问题描述
我的查询对你们大多数人来说可能听起来很简单,但它确实让我很长时间了!
table **user**
+----+-------+
| id | name |
+----+-------+
| 1 | Sanam |
+----+-------+
| 2 | Raj |
+----+-------+
| 3 | bipul |
+----+-------+
table **msg**
+----+-----------+-----------+
| id | msg | createdBY |
+----+-----------+-----------+
| 1 | Hi Raj | 1 |
+----+-----------+-----------+
| 2 | Hi bipul | 1 |
+----+-----------+-----------+
| 3 | Hi public | 1 |
+----+-----------+-----------+
table **msgToSpecificPeople**
+----+-------+-----------------+
| id | msgId | receiverId |
+----+-------+-----------------+
| 1 | 1 | 2 --raj id |
+----+-------+-----------------+
| 1 | 2 | 3 --bipul id |
+----+-------+-----------------+
现在,我想接收输出,就好像 raj 是接收者一样,然后他得到 public msg 和 1 他收到的 msg,即“hi raj”。我想忽略“hi bipul msg”。
左外连接给了我所有的记录。
SELECT m.msgContent AS MSG
FROM msg AS m
left outer JOIN msgToSpecificPeople AS p ON m.id = p.msgId and p.receiverId = 2
有人会为我解决这个问题吗?
编辑:也让我知道如何在 linq 中实现这一点
解决方案
我想你想要:
select m.*
from msg m
where exists (select 1
from msgToSpecificPeople tsp
where m.id = p.msgId and tsp.receiverId = 2
) or
not exists (select 1
from msgToSpecificPeople tsp
where m.id = p.msgId
);
推荐阅读
- javascript - 添加到购物车按钮在 Woocommerce 的单个产品页面上不起作用
- python - 为什么在 pandas 中获取反向索引的速度如此之慢?
- c# - CS0266 无法隐式转换类型 'System.Collections.Generic.IEnumerable
'到'字符串' - reactjs - 根据嵌套数据将数组拆分为块
- c++ - 自动返回值推断和 C++ 静态类型
- ruby-on-rails - 使用 Ruby on Rails 将 .zip 文件上传到 Cloudinary
- c++ - 具有接收/发送命令和请求/响应设计的 C++ 服务器
- python-3.x - BeautifulSoup .get_text() 元素不返回任何结果
- c++ - 从 dll 调用任何函数都会引发错误
- python - 如何使用 Tensorflow 操作加速 python 的 while 循环?