如何将此多计数循环编写为单个查询?

时间:2014-02-25 20:18:24

标签: php mysql count sum

我真的很难过,我尝试过使用:

sum(case when date_format(from_unixtime(l.date_updated), '%Y-%m-%d') = date_format(now(), '%Y-%m-%d') then 1 else 0 end) AS day0_leads,

在我的查询中,并没有按预期工作,所以我最终使用了这个:

    <?php

    $total_days = '14';     

    for ($i = $total_days - 1; $i >= 0; $i--)
    {
        $day = strtotime('-'.$i.' days');
        $day_string = date('n/j', $day);

        $leads = mysql_result(mysql_query("select count(*) from `leads` where date_format(from_unixtime(`date_updated`), '%m-%d-%Y') = date_format(from_unixtime($day), '%m-%d-%Y')"), 0);
        $assigns = mysql_result(mysql_query("select count(*) from `assigns` where date_format(from_unixtime(`date_assigned`), '%m-%d-%Y') = date_format(from_unixtime($day), '%m-%d-%Y') and `id_dealer` not in (1,2,3)"), 0);

        echo "['$day_string', $leads, $assigns]";

        if ($i > 0)
            echo ',';
    }

    ?>

这使得页面加载速度变慢,显然是由于不必要的查询。将此作为单个查询编写并输出结果的正确方法是什么?就像我说的那样,我已经和其他人一起尝试了一笔钱,并没有提供正确的数字。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

继承我的解决方案:

    $total_days = '14';

    // get leads count array

    $sql = mysql_query("select count(*) as `count`, `date_updated` 
                        from `leads` 
                        where date_format(from_unixtime(`date_updated`), '%Y-%m-%d') >= date_format(now() - interval $total_days day, '%Y-%m-%d')
                        group by date(from_unixtime(`date_updated`));") or die(mysql_error());

    $leads_count = array();

    while ($row = mysql_fetch_assoc($sql))
        $leads_count[date('n/j', $row['date_updated'])] = $row['count'];

    // get assigns count array

    $sql = mysql_query("select count(*) as `count`, `date_assigned` 
                        from `assigns` 
                        where date_format(from_unixtime(`date_assigned`), '%Y-%m-%d') >= date_format(now() - interval $total_days day, '%Y-%m-%d') and `id_dealer` not in (1,2,3,4)
                        group by date(from_unixtime(`date_assigned`));") or die(mysql_error());

    $assigns_count = array();

    while ($row = mysql_fetch_assoc($sql))
        $assigns_count[date('n/j', $row['date_assigned'])] = $row['count'];

    for ($i = $total_days - 1; $i >= 0; $i--)
    {
        $day = strtotime('-'.$i.' days');
        $day_string = date('n/j', $day);

        $leads = ((empty($leads_count[$day_string])) ? '0' : $leads_count[$day_string]);
        $assigns = ((empty($assigns_count[$day_string])) ? '0' : $assigns_count[$day_string]);

        echo "['$day_string', $leads, $assigns]";

        if ($i > 0)
            echo ',';
    }