繁体   English   中英

NULL 连接表的值缺失

[英]NULL Values missing of joined table

这是一个简单的例子: 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 值。 我错过了一些非常简单的东西吗?

好的 - 问题是group by contractID正确应该是group by contracts.ID 按连接发票 talbes 列 contractID 分组的group by contractID分组,这就是缺少列的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM