简体   繁体   English

在SQL计数查询中包含零?

[英]Include zeros in SQL count query?

I want to be able to return 0 when I am doing a count, I'd preferably not use joins as my query doesn't use them. 我希望能够在进行计数时返回0,我最好不要使用连接,因为我的查询不使用它们。

This is my query. 这是我的查询。

SELECT count( user_id ) as agencyLogins, 
      DATE_FORMAT(login_date, '%Y-%m-%d') as date 
FROM logins, users 
WHERE login_date >= '2015-02-10%' AND login_date < '2016-02-11%' 
AND logins.user_id = users.id 
GROUP BY DATE_FORMAT(login_date,'%Y-%m-%d')

What it does is counts the amount of times a user has logged into the website. 它的作用是计算用户登录网站的次数。 It doesn't count zeros though where as I want to know when there has been no log ins. 虽然没有登录,但我不知道在哪里可以知道零。

Please try using explicit join in the future, more readable and will make you avoid this errors. 请在将来尝试使用显式连接,更具可读性,并使您避免此错误。 What you need is a left join: 你需要的是一个左连接:

SELECT t.id,count(s.user_id) as agencyLogins, DATE_FORMAT(s.login_date, '%Y-%m-%d') as date
FROM users t
LEFT OUTER JOIN login s
ON(t.id = s.user_id)
WHERE (s.login_date >= '2015-02-10%' AND s.login_date < '2016-02-11%') or (s.user_id is null)
GROUP BY t.id,DATE_FORMAT(s.login_date,'%Y-%m-%d')

I think below SQL useful to you. 我认为下面的SQL对你有用。 2015-02-10% please remove % symbol in that string. 2015-02-10%请删除该字符串中的%符号。

    SELECT IF(COUNT(user_id) IS NULL,'0',COUNT(user_id)) as agencyLogins, DATE_FORMAT(login_date, '%Y-%m-%d') as date FROM users left join logins on logins.user_id = users.id 
    WHERE date(login_date) >= date('2015-02-10') AND date(login_date) <= date('2016-02-11')
GROUP BY DATE_FORMAT(login_date,'%Y-%m-%d')

This might be help you out 这可能对你有帮助

    SELECT SUM(agencyLogins), date FROM (
    SELECT count( user_id ) as agencyLogins, 
          DATE_FORMAT(login_date, '%Y-%m-%d') as date 
    FROM logins, users 
    WHERE login_date >= '2015-02-10%' AND login_date < '2016-02-11%' 
    AND logins.user_id = users.id 
    GROUP BY DATE_FORMAT(login_date,'%Y-%m-%d')


    UNION ALL

    SELECT 0,''
    ) AS A 
    GROUP BY DATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM