Basically I want a column to to return 0 if null. I’m using the ifnull inside a nested statement, when I run the nested statement by itself the column returns 0, but when I run the whole query I get NULL again. This is my code:
SELECT Text, Verbo, Objeto, mPosts FROM Posts
LEFT JOIN (SELECT ID, IFNULL(COUNT(*),0) AS mPosts FROM `Posts` WHERE Date >= DATE_ADD(CURDATE(), INTERVAL -30 DAY) GROUP BY `Verbo`,`Objeto`) AS B ON Posts.ID = B.ID
I could move the IFNULL to the main select statement, but I would rather not:
SELECT Text, Verbo, Objeto, IFNULL(mPosts,0) FROM Posts
LEFT JOIN (SELECT ID, COUNT(*) AS mPosts FROM `Posts` WHERE Date >= DATE_ADD(CURDATE(), INTERVAL -30 DAY) GROUP BY `Verbo`,`Objeto`) AS B ON Posts.ID = B.ID
Why I can’t do it on the nested statement? Can it can be done any other way so that I don’t have to use it on the main query?
If you are getting
NULLforIFNULL(COUNT(*),0), it is because theLEFT JOINis not matching with yourONclause ofPosts.ID = B.ID, so all values in the right table will beNULL.So yes, you will need to move
IFNULLto the top-levelSELECTclause.