2014-12-03 88 views
0

我有以下腳本,從2個表中檢索數字,進行求和,並將值更新到第3個表中。PHP/Mysql:優化查詢

$query = "SELECT (SELECT SUM(net_amount) FROM fin_costos WHERE month='1' AND group_of_costos='general' AND year_analysis='2014') + 
(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='1' AND group_of_costos='general' AND year_analysis='2014') AS total"; 

$result = mysqli_query($mysqli,$query); 

while($row = mysqli_fetch_array($result)){$valor_final = $row['total']; } 

$query_update="UPDATE fusion_analysis SET jan='$valor_final' WHERE year_for_analysis='2014' AND item_for_analysis='general' AND category='general'"; 
$result = mysqli_query($mysqli,$query_update); 

我需要爲每年的每個月運行相同的腳本。一切是除了可變「月」,改變從1至12,並且其中的值被上傳每個月在UPDATE SET(設置)exaclty相同的(「揚」,「月」,「擦傷」 ...等)

我目前只是複製和粘貼相同的腳本改變這個參數少,但我相信這是一個更聰明的方式較少的代碼行要做到這一點我有PHP的

回答

0

請參閱日期功能:

$query = "SELECT (SELECT SUM(net_amount)" 
    . " FROM fin_costos" 
    . " WHERE month='".date('n')."'" 
    ." AND group_of_costos='general' AND year_analysis='".date("Y")."') +" 
    ."(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='".date('n')."'" 
    . " AND group_of_costos='general' AND year_analysis='".date("Y")."') AS total"; 

$query_update="UPDATE fusion_analysis" 
    . " SET `". strtolower(date('M'))."`='$valor_final'" 
    . " WHERE year_for_analysis='".date("Y")."'" 
    . " AND item_for_analysis='general'" 
    . " AND category='general'"; 

注:

Y - 每年的完整數字表示,4位像2014

n - 一個月的數字表示,沒有前導零1 - 12

M - 一個月的短文本表示,三個字母揚通過十二月

對於每月簡短的文字我已經使用了strtolower功能,使其小寫。

UPDATE

基於OP評論:

for ($i = 1; $i <= 12; $i++) { 
    $query = "SELECT (SELECT SUM(net_amount)" 
     . " FROM fin_costos" 
     . " WHERE month='" . $i . "'" 
     . " AND group_of_costos='general' AND year_analysis='" . date("Y") . "') +" 
     . "(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='" . $i . "'" 
     . " AND group_of_costos='general' AND year_analysis='" . date("Y") . "') AS total"; 

    $result = mysqli_query($mysqli, $query); 
    $row = mysqli_fetch_assoc($result); 

    $valor_final = $row['total']; 

    $monthName = strtolower(date('M', strtotime(date("Y") . "-" . str_pad($month,2, "0", STR_PAD_LEFT) . "-" . date("01")))); 

    $query_update = "UPDATE fusion_analysis" 
     . " SET `" . $monthName . "`=' " . $valor_final . "'" 
     . " WHERE year_for_analysis='" . date("Y") . "'" 
     . " AND item_for_analysis='general'" 
     . " AND category='general'"; 
    mysqli_query($mysqli, $query_update); 
} 
+0

感謝。對於我所看到的,只會在當月運行更新。如果日期是 - 例如8月,會發生什麼,但用戶會從1月份開始更改費用。那麼這個成本不會被更新。 – user2952715 2014-12-03 11:33:48

+0

然後,您需要在頁面上創建一個表單,用戶可以在其中設置日期。但是你寫了這樣的話:「我需要爲每年的每個月運行相同的腳本。確切地說,' – vaso123 2014-12-03 11:37:58

+0

',但事情是腳本應該在同一時間運行12個月,不管使用日期。 – user2952715 2014-12-03 11:45:25