2014-02-25 40 views
0

我真的難倒在這裏,我已經嘗試使用:如何將此多重計數循環寫入單個查詢?

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 ','; 
    } 

    ?> 

這會導致頁面加載速度變慢,顯然是由於不必要的查詢。將此作爲單個查詢並輸出結果的正確方法是什麼?就像我說過的,我已經嘗試了與其他人的總和,但沒有產生正確的數字。

任何幫助將不勝感激。

+0

你能解釋一下你想算什麼? – fthiella

回答

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 ','; 
    }