首页 > 解决方案 > 在 MySQL 中加入查询结果

问题描述

我在 MySQL 数据库中工作。

我有三张桌子。1 , 2 & 3

我想在 id 上加入表 2 和表 3 到表 1 的结果。我想保留表 1 的所有条目,并在调用 id 上加入 2 和 3 的结果之后,并且它不匹配的地方有一个空值。

Table 1 has callid
Table 2 has callid and invoiceid
Table 3 has invoiceid and customerid

因此,在 invoiceid 上加入表 2 和 3 并按 customerid = xyz 过滤,然后将结果加入到 callid 上的表 1。表 1 还将有一个 Where 子句过滤日期

结果看起来像这样

callid   customerid
  123       xyz
  124       xyz
  125       null
  126       xyz

提前谢谢你

标签: mysqlsqljoin

解决方案


我想你在描述left join

select . . .
from table1 t1 left join
     table2 t2
     on t1.callid = t2.callid left join
     table3 t3
     on t3.invoiceid = t2.invoiceid;

您可以在on子句中过滤客户 ID:

from table1 t1 left join
     table2 t2
     on t1.callid = t2.callid left join
     table3 t3
     on t3.invoiceid = t2.invoiceid and t3.customerid = ?;

但是,这可能不是您想要的。您可能想要过滤内部连接,然后执行以下操作left join

select . . .
from table1 t1 left join
     (table2 t2 join
      table3 t3
      on t3.invoiceid = t2.invoiceid
     )
     on t1.callid = t2.callid and
        t3.customerid = ?

推荐阅读