MYSQL HAVING 包含不存在的条目

发布于 2025-01-02 20:17:58 字数 305 浏览 1 评论 0原文

我想选择最大值 s2.maxcol 或 0(如果没有条目)。 到目前为止,这是有效的,但如果没有相应的条目,则不会返回:

SELECT MAX( s2.maxcol) AS max_col, s1 . *
FROM table AS s1
LEFT JOIN table AS s2 ON s2.parent = s1.id
GROUP BY s1.id
HAVING max_col <100

但我也希望左连接返回没有相应条目的行(所以 max(s2.maxcol) 应该为 0。

我该如何解决这个问题?

i want to select a max of s2.maxcol or 0 if there are no entries.
So far this works, but if there is no corresponding entry it is not returned:

SELECT MAX( s2.maxcol) AS max_col, s1 . *
FROM table AS s1
LEFT JOIN table AS s2 ON s2.parent = s1.id
GROUP BY s1.id
HAVING max_col <100

But i also want to have the rows where the left join returns no corresponding entry (so max(s2.maxcol) should be 0.

How can i solve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九命猫 2025-01-09 20:17:59

我只是快速浏览了一下,现在就必须离开。但也许COALESCE可能会有所帮助。这是 信息

也许是这样的? (未经测试!)

SELECT COALESCE(MAX(s2.maxcol), 0) AS max_col, s1 . *
FROM table AS s1
LEFT JOIN table AS s2 ON s2.parent = s1.id
GROUP BY s1.id
HAVING max_col <100

希望有帮助。再见!

I just gave this a quick look and have to leave right now. But maybe COALESCE might help. Here is the info

Maybe something like this? (UNTESTED!)

SELECT COALESCE(MAX(s2.maxcol), 0) AS max_col, s1 . *
FROM table AS s1
LEFT JOIN table AS s2 ON s2.parent = s1.id
GROUP BY s1.id
HAVING max_col <100

Hope that helps. Bye!

蓝戈者 2025-01-09 20:17:59

HAVING max_col <100 更改为 HAVING max_col is NULL or max_col <100
效果完美。

changed HAVING max_col <100 to HAVING max_col is NULL or max_col <100
which works flawlessly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文