首页 > 解决方案 > 如何忽略表 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 中实现这一点

标签: mysqlsqllinqjoinouter-join

解决方案


我想你想要:

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

推荐阅读