空值缺少联接表

时间:2020-06-24 08:38:44

标签: mysql join temp-tables

这是一个简单的示例:sqlfiddle.com/#!9/8087c5/1

我有以下查询:

select
    contracts.ID as contractID,
    departments.ID as departmentID,
    max(invoices.timestamp) as timestamp
from contracts
    left join departments on departments.ID = contracts.departmentID and departments.accountingType > 0
    left join invoices on contracts.ID = invoices.contractID
group by contractID
having departmentID is not null;

我希望得到如下结果:

+------------+--------------+---------------------+
| contractID | departmentID | timestamp           |
+------------+--------------+---------------------+
| 101        | 301          | NULL                |
+------------+--------------+---------------------+
| 102        | 302          | NULL                |
+------------+--------------+---------------------+
| 103        | 303          | 2020-05-01 11:11:00 |
+------------+--------------+---------------------+

相反,我得到了:

+------------+--------------+---------------------+
| contractID | departmentID | timestamp           |
+------------+--------------+---------------------+
| 103        | 303          | 2020-05-01 11:11:00 |
+------------+--------------+---------------------+

我不明白为什么查询会删除最后一个左连接表的NULL值。我是否缺少一些简单的东西?

1 个答案:

答案 0 :(得分:0)

好的-问题是group by contractID是正确的group by contracts.IDgroup by contractID按合并的发票表列contractID分组,这就是缺少列的原因。