0

Im making a SELECT query for two tables.

Tables:

  • ec_events
  • ec_calendar

enter image description here

Select QUERY:

SELECT MONTH(`ec_calendar`.`Day`) AS Month ,COUNT(`ID_Event`) AS Count 
FROM `ec_events`,`ec_calendar` 
WHERE `ec_events`.`FK_Day`=`ec_calendar`.`ID_Day` AND YEAR(`ec_calendar`.`Day`) = 2015 
GROUP BY MONTH(`ec_calendar`.`Day`)

And the result:

enter image description here

The only problem here is May (5. month). On the result image you can see, that was ignored, because in ec_calendar is no entry for this month. Many times better will be, if 0 could be returned. So the table will loks so:

....
3  15
4  7
5  0
6  10
7  3
...

Is there any way to provide it?

Marc Delisle
  • 8,879
  • 3
  • 29
  • 29
Bullman
  • 318
  • 1
  • 4
  • 13

2 Answers2

4

Use a LEFT JOIN:

SELECT MONTH(`ec_calendar`.`Day`) AS Month ,COUNT(`ID_Event`) AS Count 
FROM `ec_events`
LEFT JOIN `ec_calendar` 
ON `ec_events`.`FK_Day`=`ec_calendar`.`ID_Day` 
WHERE YEAR(`ec_calendar`.`Day`) = 2015 
GROUP BY MONTH(`ec_calendar`.`Day`)

A LEFT JOIN will keep all records from your left table and fill in NULLs where it doesn't match to your right table.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
1

You have to create a table allMonth with all months from 1..12, maybe you also will add year field if need it.

This sample will give you an idea of fill the table with date ranges

allMonth

 month_id
 year_id
 name

Query

SELECT AM.month_id AS Month, COUNT(`ID_Event`) AS Count 
FROM  allMonth  AM
LEFT JOIN `ec_calendar` EC
       ON AM.month_id = MONTH(EC.`Day`)
INNER JOIN `ec_events`  EV
       ON EV.`FK_Day`= EC.`ID_Day`
      AND YEAR(EC.`Day`) = 2015 
GROUP BY AM.month_id

Aditional TIPS:

  • Always try to use alias to improve reading
  • Learn how to use explicit join syntax. Aaron Bertrand did some writting about it
Community
  • 1
  • 1
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • I dont think, that make another table is good solution. Here must be simplier way, but thanks for your time and answer. – Bullman Oct 16 '15 at 22:46
  • @Bullman, Sorry but there isnt. I have answer this same question multiple times. With users missing `years`. `months` or `days` In all cases the answer is create a table. And use the store procedure I include to fill the table. – Juan Carlos Oropeza Oct 16 '15 at 22:49
  • For example include a table with `100` years of days have only `36,500` so is very small, And believe me I did the math and isnt expensive neither on time executions. A table of months have only `1200 rows` – Juan Carlos Oropeza Oct 16 '15 at 22:52
  • @Bullman think about it. How would you group something when isnt there? – Juan Carlos Oropeza Oct 16 '15 at 22:56