如果没有结果列,则获取0值 - MySQL

时间:2014-09-20 08:07:30

标签: mysql sql select

我有以下查询

SELECT COUNT( iContactId ) AS Users, DATE( dCreatedAt ) AS ActivityDate 
FROM contacts WHERE iAppId =".$iAppId." 
AND DATE(dCreatedAt) IN (CURRENT_DATE(), CURRENT_DATE()-1 ) 
GROUP BY ActivityDate 

由此我得到了

Users |ActivityDate
1     |2014-09-19

如果没有匹配行,我想要0

例如

Users |ActivityDate
0     |CURRENT_DATE()
0     | CURRENT_DATE()-1

我该怎么做。

4 个答案:

答案 0 :(得分:1)

<强> QUERY

SELECT
COUNT(C.iContactId) AS Users,
DATE(C.dCreatedAt) AS ActivityDate 
FROM
contacts C
    LEFT OUTER JOIN
(
    SELECT CURRENT_DATE() AS Dates FROM dual
        UNION
    SELECT CURRENT_DATE() - 1 AS Dates FROM dual
) D
    ON
        D.Dates = DATE(C.dCreatedAt)
WHERE
C.iAppId =".$iAppId."
GROUP BY
C.ActivityDate

答案 1 :(得分:0)

<强> QUERY

SELECT 
ISNULL( iContactId ,0) AS Users, 
DATE( dCreatedAt ) AS ActivityDate 
FROM contacts 
WHERE iAppId =".$iAppId." 
AND DATE(dCreatedAt) IN (CURRENT_DATE(), CURRENT_DATE()-1 ) 
GROUP BY ActivityDate 

答案 2 :(得分:0)

你可以使用联盟

SELECT COUNT( iContactId ) AS Users, CURRENT_DATE() AS ActivityDate
FROM contacts WHERE iAppId =".$iAppId." 
AND DATE(dCreatedAt) = CURRENT_DATE()
UNION
SELECT COUNT( iContactId ) AS Users, CURRENT_DATE() - 1 AS ActivityDate 
FROM contacts WHERE iAppId =".$iAppId." 
AND DATE(dCreatedAt) = CURRENT_DATE() - 1

答案 3 :(得分:0)

在大多数答案中,这是使用日期减法:

SELECT CURRENT_DATE() - 1
-> 20140919

这将导致隐式类型转换,并且日期将被转换为int,而是使用它:

SELECT CURRENT_DATE - INTERVAL 1 DAY
-> 2014-09-19

我的解决方案

SELECT
    d.ActivityDate,
    COUNT(c.iContactId) Users
FROM
    (
    SELECT CURRENT_DATE - INTERVAL 1 DAY ActivityDate FROM DUAL
    UNION
    SELECT CURRENT_DATE FROM DUAL
    ) d
LEFT JOIN
    contacts c
    ON DATE(c.dCreatedAt) = d.ActivityDate
    AND c.iAppId = " . $iAppId . "
GROUP BY d.ActivityDate