即使一个表中的count为0,MYSQL也会显示结果

时间:2013-03-04 23:46:07

标签: mysql sql count

如果计数为0,我试图让计数显示0,例如

Curent结果:

Extension    Calls
1234         1
1345         2

但我想要它显示:

Extension    Calls
1234         1
1245         0
1345         2

SELECT c.Extension,count(c.Extension),0 as Calls 
from call c
where c.callType=3 
and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00'))
group by c.Extension

3 个答案:

答案 0 :(得分:2)

联合中的第一个查询已经在问题中可用,其中具有给定时间和在给定时间内发生的扩展即将到来。第二个查询只是否定了调用次数为零的情况。

        SELECT c.Extension,count(c.Extension) as Calls 
        from call c
        where c.callType=3 
        and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00'))
        group by c.Extension
    union
        SELECT c.Extension,0 as Calls 
        from call c
        where (c.callType=3 
            and (c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00'))) = false
        group by c.Extension
    order by Extension

答案 1 :(得分:0)

SELECT
    A.Extension,
    IFNULL(B.ExtensionCount,0) Calls
FROM
(
    SELECT DISTINCT Extension
    FROM call WHERE callType=3 AND
    StartTime BETWEEN TIMESTAMP(CURDATE(),'06:30:00')
    AND TIMESTAMP(CURDATE(),'07:00:00')
) A
LEFT JOIN
(
    SELECT Extension,COUNT(1) ExtensionCount
    FROM call WHERE callType=3 AND
    StartTime BETWEEN TIMESTAMP(CURDATE(),'06:30:00')
    AND TIMESTAMP(CURDATE(),'07:00:00')
    GROUP BY Extension
) B
USING (Extension);

请确保您拥有这些索引

ALTER TABLE call ADD INDEX
callType_StartTime_Extension_ndx (callType,StartTime,Extension);
ALTER TABLE call ADD INDEX Extension_ndx (Extension);

这样,查询不会从表中读取。它将从索引中读取所有内容。

答案 2 :(得分:0)

您可以使用条件聚合执行此操作:

SELECT c.Extension,
       sum(case when c.callType=3 and
                     c.StartTime between TIMESTAMP(CURDATE(),'06:30:00') and TIMESTAMP(CURDATE(),'07:00:00')
                then 1
                else 0
           end) as calls
from call c
group by c.Extension