如何忽略 table 1 中的记录(其 fk-reference 必须存在于 table 2 中)但条件不满足
How to ignore records from table 1 (whoes fk-refrence must be present in table 2) but where condition does not satisfies
我的查询对你们大多数人来说可能听起来很简单,但它确实让我着迷了很长一段时间!
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
);
我的查询对你们大多数人来说可能听起来很简单,但它确实让我着迷了很长一段时间!
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
);