简体   繁体   中英

MYSQL Count, LEFT OUTER JOIN with 0 count on a simple case

Considering the two following sample tables

TABLE 1 : 'users'

ID    REGISTER_TIME    FIRSTNAME    LASTNAME    OPERATION_ID

1     1401789877       John         Doe         29
2     1401789879       Jack         Doe         29
3     1401789878       Pete         Doe         29

(Note that the register_time column is stored as INT(11))

TABLE 2 : 'calendar_days'

ID    DAY
1     2011-01-01
...   ....
n     2030-31-12

I have the following MySQL query which is working great :

SELECT d.day, COUNT(d.day)
FROM calendar_days AS d
LEFT OUTER JOIN users AS l ON DATE(FROM_UNIXTIME(l.`register_time`)) = d.day
WHERE l.`operation_id` = 29
GROUP BY d.day;

But it doesn't keep the days where count equals zero :

day;COUNT(d.day)

2014-05-07;1
2014-05-09;1
2014-05-12;11
2014-05-13;2713
2014-05-14;2631

What i want :

2014-05-07;1
**2014-05-08;0**
2014-05-09;1
2014-05-12;11
2014-05-13;2713
2014-05-14;2631

I feel like i'm close from the truth, I've tried any join possible left outer, right outer, still no empty results.

Your where clause turns your left join into an inner join since you use a condition on the joined table. Try

SELECT d.day, COUNT(d.day)
FROM calendar_days AS d
LEFT OUTER JOIN users AS l ON DATE(FROM_UNIXTIME(l.`register_time`)) = d.day
                           AND l.`operation_id` = 29
GROUP BY d.day;

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