MySQL Group by用零计数和左外部联接

时间:2019-01-03 01:01:48

标签: mysql sql

我在下面的查询中获得特定日期的用户注册,该功能可以找到,但当该天的用户注册计数为零时,我希望它显示为零计数。但是,似乎正在跳过该条目,

SELECT count( * ) AS total, a.Date AS created_dates
                FROM (

                    SELECT (CURDATE() - INTERVAL c.number DAY) AS date
FROM (SELECT singles + tens + hundreds number FROM 
( SELECT 0 singles
UNION ALL SELECT   1 UNION ALL SELECT   2 UNION ALL SELECT   3
UNION ALL SELECT   4 UNION ALL SELECT   5 UNION ALL SELECT   6
UNION ALL SELECT   7 UNION ALL SELECT   8 UNION ALL SELECT   9
) singles JOIN 
(SELECT 0 tens
UNION ALL SELECT  10 UNION ALL SELECT  20 UNION ALL SELECT  30
UNION ALL SELECT  40 UNION ALL SELECT  50 UNION ALL SELECT  60
UNION ALL SELECT  70 UNION ALL SELECT  80 UNION ALL SELECT  90
) tens  JOIN 
(SELECT 0 hundreds
UNION ALL SELECT  100 UNION ALL SELECT  200 UNION ALL SELECT  300
UNION ALL SELECT  400 UNION ALL SELECT  500 UNION ALL SELECT  600
UNION ALL SELECT  700 UNION ALL SELECT  800 UNION ALL SELECT  900
) hundreds
ORDER BY number DESC) c  
WHERE c.number BETWEEN 0 and 364

    ) a
    LEFT OUTER JOIN `users_tp` u
        ON DATE(u.register) = a.Date
WHERE
    ( a.Date  BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() )
    AND u.origin_reg = 'mobile'
    AND u.step!=5   
GROUP BY a.Date
               ORDER BY a.Date ASC;

2 个答案:

答案 0 :(得分:3)

问题来自JOIN:它是LEFT JOIN,这是您想要的,但是WHERE子句指的是要联接的表:因此,此表现得像INNER JOIN

要解决此问题,您需要将联接表中的条件从WHERE子句的ON子句移到JOIN的{​​{1}}子句。

更改此内容:

LEFT OUTER JOIN `users_tp` u
    ON DATE(u.register) = a.Date
WHERE
    ( a.Date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() )
    AND u.origin_reg = 'mobile'
    AND u.step!=5   

收件人:

LEFT OUTER JOIN `users_tp` u
    ON  DATE(u.register) = a.Date
    AND u.origin_reg = 'mobile'  
    AND u.step!=5
WHERE
    a.Date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

答案 1 :(得分:0)

另一种解决方案:

SELECT count(register ) AS total,a.date AS created_dates from 
(SELECT (CURDATE() - INTERVAL c.number DAY) AS date
FROM (SELECT singles + tens + hundreds number FROM 
( SELECT 0 singles
UNION ALL SELECT   1 UNION ALL SELECT   2 UNION ALL SELECT   3
UNION ALL SELECT   4 UNION ALL SELECT   5 UNION ALL SELECT   6
UNION ALL SELECT   7 UNION ALL SELECT   8 UNION ALL SELECT   9
) singles JOIN 
(SELECT 0 tens
UNION ALL SELECT  10 UNION ALL SELECT  20 UNION ALL SELECT  30
UNION ALL SELECT  40 UNION ALL SELECT  50 UNION ALL SELECT  60
UNION ALL SELECT  70 UNION ALL SELECT  80 UNION ALL SELECT  90
) tens  JOIN 
(SELECT 0 hundreds
UNION ALL SELECT  100 UNION ALL SELECT  200 UNION ALL SELECT  300
UNION ALL SELECT  400 UNION ALL SELECT  500 UNION ALL SELECT  600
UNION ALL SELECT  700 UNION ALL SELECT  800 UNION ALL SELECT  900
) hundreds
ORDER BY number DESC) c  
WHERE c.number BETWEEN 0 and 364)a 

left join 

(SELECT * from users_tp where origin_reg = 'mobile'
    AND step!=5) u

on DATE(u.register) = a.Date
where
(a.Date  BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() )
GROUP BY a.Date
               ORDER BY a.Date ASC;