Mysql 左连接 sum() 不返回所有项目

标签 mysql having

此请求从 tcredit 返回的项目高于 tcredit_order 项目中项目的总和。 但我不会退回不在 tcredit_order 中的商品。 我测试了其他方法,例如子查询,但它不起作用,而且这看起来更简单。

SELECT * FROM tcredit
LEFT JOIN tcredit_order ON tcredit.id_credit=tcredit_order.id_credit
GROUP BY tcredit.id_credit
HAVING tcredit.credit > SUM(tcredit_order.credit)
ORDER BY tcredit.date_limit ASC

最佳答案

这是一个常见的陷阱:一旦您添加一个关于 LEFT JOINed 表的 WHERE - ,您就可以在逻辑上隐式地将其设为内连接,只要满足以下条件即可您没有添加有关 NULL 的提示。

SELECT * FROM tcredit
LEFT JOIN tcredit_order ON tcredit.id_credit=tcredit_order.id_credit
GROUP BY tcredit.id_credit
HAVING (tcredit.credit > SUM(tcredit_order.credit) or (SUM(tcredit_order) is null))  
ORDER BY tcredit.date_limit ASC

这应该可以解决问题。请记住:1 > 0 为 true,但 1 > NULL 为 NULL 并且不为 true。

根据评论,coalesce 有点酷(我通常只将它用于较长的链)。

HAVING (tcredit.credit > COALESCE(SUM(tcredit_order.credit),0))

或者,如果您担心同事可能不知道,只需 IFNULL

HAVING (tcredit.credit > IFNULL(SUM(tcredit_order.credit),0))

关于Mysql 左连接 sum() 不返回所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23455002/

相关文章:

mysql - 在sql中对内容进行分组

php - Codeigniter Active record Join 2 x From in 语句

MySQL/Ruby on Rails - 如何将 "SUM"写入 :has_many case

postgresql - 反馈我写的查询 [PostgreSQL]

mysql - 将 AVG 与 HAVING 一起使用

python - 如何在 Linux 中为 MySQL+Python 创建可执行文件?

mysql - 如何比较mysql中两个表中的值

mysql - 更新后用 2 个表触发

MYSQL HAVING(不)与 ROW_NUMBER() 为什么它返回不同的行数

mysql - 计算患者(女性和男性)第一次咨询的次数以及随后的咨询次数