[英]Passing sql variables from INNER JOIN SQL query to PHP script
我有以下INNER JOIN查詢:
SELECT b.*, c.date2
FROM (
SELECT a.work, a.amount,
COUNT(*) totalCount,
SUM(Amount) totalAmount
FROM work_times a WHERE Organisation=?
GROUP BY a.work, a.amount
) b
INNER JOIN
(
SELECT a.work, a.amount, DATE_FORMAT(Date,'%D %M %Y') date2,
date
FROM work_times a
) c ON b.work = c.work and b.amount=c.amount
ORDER BY b.work, b.totalCount, c.date
你可以看到它在行動上SQL搗鼓一個示例表在這里 。
我的目標是返回以下內容:
5 consultancy sessions @ £50 each: £250
1st February 2013
8th February 2013
15th February 2013
22nd February 2013
1st March 2013
3 therapy sessions @ £40 each: £120
2nd February 2013
9th February 2013
16th February 2013
2 therapy sessions @ £20 each: £40
3rd February 2013
10th February 2013
但是使用以下PHP:
$stmt->bind_param("s", $name1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($work,$amount,$count,$total_group,$date);
while ($stmt->fetch()) {
if ($count>1) {
echo $count." ".$work."s @ £".$amount." each<br><br>";
echo date("jS F Y",strtotime($date))."<br><br>";
$total_work=$total_work+$total_group;
}
else {
echo $count." ".$work." @ £".$amount."<br><br>";
echo date("jS F Y",strtotime($date))."<br><br>";
$total_work=$total_work+$total_group;
}
}
我為每一行獲得一行,而不是分組,即:
5 Consultancy Sessions @ £50.00
1st February 2013
5 Consultancy Sessions @ £50.00
8th February 2013
5 Consultancy Sessions @ £50.00
15th February 2013
...etc
我不知道如何修改我的PHP以獲得所需的輸出。
當前輸出
5 Consultancy Sessions @ £50.00
1st February 2013
8th February 2013
15th February 2013
22nd February 2013
1st March 2013
2nd February 2013
9th February 2013
16th February 2013
3rd February 2013
10th February 2013
問題似乎在於你要為每一行調用“頭”。 因此,您應首先檢查它是否已被調用。 我希望以下內容可以幫助您:
$stmt->bind_param("s", $name1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($work,$amount,$count,$total_group,$date);
$last_work = "";
while ($stmt->fetch()) {
if($work != $last_work || $amount != $last_amount){
if ($count>1) {
echo "<br>".$count." ".$work."s @ £".$amount." each<br><br>";
}
else {
echo "<br>".$count." ".$work." @ £".$amount."<br><br>";
}
$last_work = $work;
$last_amount = $amount;
}
echo date("jS F Y",strtotime($date))."<br>";
$total_work=$total_work+$total_group;
}
我將echo date
和$total_work
外面,因為它們在兩種情況下均被調用( $count >1
和else
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.