简体   繁体   中英

MYSQL HAVING with nonexistent entries

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?

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!

HAVING max_col <100更改为HAVING max_col is NULL or max_col <100 ,这可以正常工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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