2011-12-28 54 views
3

1つのクエリで以下のクエリを実行し、その結果を以下のように取得するにはどうすればよいですか?1つのクエリで複数のクエリを実行する方法

// 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を使用することができます - しかし、あなたはその場合にはあなたの代わりに

1

あなたはmysqliのドライバの代わりのMySQLを試してみましたが、1 /文グループの4つのレコードを取得しますので、結果セットを反復処理する必要がありますか?

を見てみましょう:mysqli_multi_query

セミコロンで連結された1つまたは複数のクエリを実行します。

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 
関連する問題