【问题标题】:How to ignore records from table 1 (whoes fk-refrence must be present in table 2) but where condition does not satisfies如何忽略表 1 中的记录(其 fk 引用必须存在于表 2 中)但条件不满足
【发布时间】:2019-11-03 14:48:21
【问题描述】:

我的查询对你们大多数人来说可能听起来很简单,但它确实吸引了我很长一段时间!

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 中实现这一点

【问题讨论】:

  • 你能告诉我们你想要什么输出吗?
  • 只需切换msgToSpecificPeoplemsg即可。

标签: mysql sql linq join outer-join


【解决方案1】:

我想你想要:

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

【讨论】:

  • 成功了!谢谢..我也可以对 linq 做同样的事情吗?
  • @Sanam 。 . .我希望如此,但我不知道 linq 语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2023-03-28
  • 2011-08-24
  • 2017-03-31
  • 2012-10-27
  • 2012-10-27
  • 2019-11-01
相关资源
最近更新 更多