我的查询对你们大多数人来说可能听起来很简单,但它确实让我着迷了很长一段时间!
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)消息和 1 他收到的消息,即“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
);
关于mysql - 如何忽略表 1 中的记录(其 fk 引用必须存在于表 2 中)但条件不满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56691783/