Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Return 0 From a MySQL db When the Term in the Where Clause is Not in the database?

Tags:

null

select

mysql

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.

like image 867
Laxmidi Avatar asked Oct 14 '22 08:10

Laxmidi


2 Answers

SELECT COALESCE(SUM(incidents), 0), 'Old Town'
FROM `myTable`
WHERE neighborhoods = 'Old Town'
like image 138
Mark Byers Avatar answered Oct 31 '22 18:10

Mark Byers


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
like image 41
OMG Ponies Avatar answered Oct 31 '22 18:10

OMG Ponies