How do I get my mysql database to return 0 if the neighborhood in the WHERE clause doesn't exist? So in the example below, Old Town is not in the database. I'd like the database to return 0 incidents instead of an empty result.
SELECT incidents,
neighborhoods
FROM `myTable`
WHERE neighborhoods ='Old Town'
I also tried
SELECT IFNULL(incidents,0),
IFNULL(neighborhoods,0)
FROM `myTable`
WHERE neighborhoods ='Old Town'
Any suggestions would be really appreciated.
SELECT COALESCE(SUM(incidents), 0), 'Old Town'
FROM `myTable`
WHERE neighborhoods = 'Old Town'
My take on your issue is to construct a derived table of the neighborhoods
values you hope to find, and LEFT JOIN
to the actual table:
SELECT x.neighborhoods,
COALESCE(mt.incidents, 0) AS incidents
FROM (SELECT 'Old Town' AS neighborhoods
FROM DUAL
UNION ALL
SELECT 'New Town'
FROM DUAL) x
LEFT JOIN MYTABLE mt ON mt.neighborhoods = x.neighborhoods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With