2011-12-28 52 views
3

如何在單個查詢中完成以下查詢並按照下面的方式獲取結果?如何在單個查詢中完成多個查詢

// Begining of January 

$ob = mysql_query(" SELECT SUM(salary_amount) AS total FROM teacherexpense WHERE month(disburse_date)='01' AND year(disburse_date)='$year' "); 
$nt = mysql_fetch_assoc($ob); 
$salaryamount= $nt['total']; 


$ob = mysql_query(" SELECT SUM(other_expense_amount) AS expenseamount FROM otherexpense WHERE month(other_expense_date)='01' AND year(other_expense_date)='$year' "); 
$nt = mysql_fetch_assoc($ob); 
$expenseamount= $nt['expenseamount']; 

$jk = mysql_query(" SELECT SUM(amountpaid) AS revenue FROM studentpayment1 WHERE month(received_date)='01' AND year(received_date)='$year' "); 
$t = mysql_fetch_assoc($jk); 
$revenue= $t['revenue']; 

$ob = mysql_query(" SELECT SUM(other_earning_amount) AS otherearningamount FROM otherearning WHERE month(other_earning_date)='01' AND year(other_earning_date)='$year' "); 
$nt = mysql_fetch_assoc($ob); 
$otherearningamount= $nt['otherearningamount']; 


$January= ($revenue+$otherearningamount)-($salaryamount+$expenseamount); 
// End of January 
+1

你可以使用'UNION',每一行都將代表不同的查詢。 –

回答

1

將其存入存儲過程? PHP的數據庫驅動程序不會讓你運行多個查詢,出於安全原因。

0

你可以使用MySQL UNION - 但你必須遍歷結果集,因爲在這種情況下,你會得到4條記錄,而不是一個/語句組

1

您是否嘗試過mysqli的驅動程序,而不是MySQL的?

看看:mysqli_multi_query

執行它們由分號連接起來的一個或多個查詢。

1
SELECT 'withdrawals' t, SUM(amount) sum 
FROM withdrawals 
UNION 
SELECT 'statement' t, SUM(amount) sum 
FROM statement 

enter image description here

while($row = mysql_fetch_assoc($result)) 
{ 
    $total[$row['t']] = $row['sum']; 
} 

echo $total['withdrawals']; # 100 
echo $total['statement']; # 624.x