如果一天没有结果,MySQL查询得到0

时间:2012-07-30 05:52:19

标签: php mysql flot

我在flot中创建了一个折线图,除了没有结果的日子之外,我已经全部工作了,我需要他们回来结果0 +日期。这可能在mysql中吗?这是我目前的查询:

$chartQuery = "SELECT count(date) as counted_leads, UNIX_TIMESTAMP(date) as time FROM enquiries WHERE visibility != 'deleted' group by date";

或者我需要在我的PHP中执行此操作吗?这是我的代码:

<?php 
        $last_key = end(array_keys($chartResults));
        foreach ($chartResults as $item => $value)
        {
            $timestamp = round($value['time'] * 1000);

            if ($item == $last_key)
            {
                // last element
                echo '['.$timestamp.', '.htmlentities($value['counted_leads']).']';
            }
            else 
            {
                // not last element
                echo '['.$timestamp.', '.htmlentities($value['counted_leads']).'],';
            }
        }
        unset($value);
        ?>

2 个答案:

答案 0 :(得分:2)

SELECT 
     ifnull(count(date),0) as counted_leads, 
     UNIX_TIMESTAMP(date) as time 
FROM enquiries WHERE visibility != 'deleted' 
group by date

如果为默认值

,则使用null

答案 1 :(得分:0)

我认为这就是你要找的东西:

SELECT time, SUM(counted_leads) AS counted_leads
FROM(
        SELECT UNIX_TIMESTAMP(date) AS time, count(1) AS counted_leads
        FROM enquiries
        WHERE visibility != 'deleted'
        GROUP BY time

        UNION ALL

        SELECT a.Date AS time, 0 AS counted_leads
        FROM (
            SELECT CURDATE() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Date
            FROM (SELECT 0 AS a 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) AS a
            CROSS JOIN (SELECT 0 AS a 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) AS b
            CROSS JOIN (SELECT 0 AS a 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) AS c
        ) a
        WHERE a.Date BETWEEN (SELECT MIN(date) FROM enquiries) AND (SELECT MAX(date) FROM enquiries)
) a
GROUP BY time;