2015-12-01 73 views
-1

我有一系列SQL查詢來輸出所有12個月的數值。最小化一系列SQL查詢

$chartIncomejan  = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-01%'"); 
$chartIncomefeb  = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-02%'"); 
$chartIncomemar  = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-03%'"); 
$chartIncomeapr  = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on LIKE '%2015-04%'"); 
... 

這是我的輸出

if ($chartIncomejan['num'] > '0') { echo $chartIncomejan['num'].','; } else { echo '0,'; } 
if ($chartIncomefeb['num'] > '0') { echo $chartIncomefeb['num'].','; } else { echo '0,'; } 
if ($chartIncomemar['num'] > '0') { echo $chartIncomemar['num'].','; } else { echo '0,'; } 
if ($chartIncomeapr['num'] > '0') { echo $chartIncomeapr['num'].','; } else { echo '0,'; } 
... 

它作爲回聲逗號分隔值列表碼...等

我想這個代碼減少到最小可能的代碼量,但我不知道從哪裏開始。我應該做陣列嗎?也許是一個foreach語句?如果你可以展示一個例子(不一定用我的代碼),那也會很有幫助。

+0

我不知道爲什麼我會被低估。這是一個真正嘗試學習最佳實踐的人的合理問題... –

+0

什麼數據類型是'paid_on'列 – RiggsFolly

+0

'paid_on'是TIMESTAMP –

回答

2

你也許能夠使用的東西像這樣(未經測試)

/* Assuming mysqli */ 

$sql="select *, sum(`rent_amount`) as 'num' from `transaction` 
    where year(`paid_on`)=year(now()) 
    group by month(`paid_on`);"; 

$res=$conn->query($sql); 

if($res){ 
    $chartIncomes=$res->fetch_all(); 

    /* process array to your needs */ 
    echo '<pre>',print_r($chartIncomes,true),'</pre>' 
} 

$conn->close(); 
+0

這幫助我解決了我的問題。謝謝! –

1

爲什麼不改變條件並收集一個查詢中的所有數據?

$chartIncome = $query->fetch("SELECT *, SUM(rent_amount) AS 'num' FROM transaction WHERE paid_on BETWEEN '2015-01-01' AND '2015-04-31'"); 

這是假設你的列paid_onDATE。您將獲得$chartIncome所有數據,然後你只是這樣做:

echo $chartIncome['num'].','; 

的情況是沒有必要的,如果你只是始終顯示結果

+0

'paid_on'實際上是一個TIMESTAMP。如果我要做'BETWEEN'2015-01-01 00:00:00'和'2015-04-31 23:59:59''這樣的事情嗎?我試了一下,但是在一個列表中查找每個月的總和時輸出了一個大數目。 –