[英]mysql query - error showing mysql results using inner join
我有 2 個要合並的表。 我想打印所有產品及其相應的總數量和總金額。
這就是我所擁有的。
//Product Table
productID productName
1 A
2 B
3 C
//Order Record (This came from 2 tables that I have successfully merged)
orderID productID quantity amount
1 1 5 100
2 2 2 50
3 2 3 150
我想做這個
productID productName totalQuantity totalAmount
1 A 8 250
2 B 2 50
3 C 0 0
//instead of 0 for total Quantity and total Amount, it shows 2 and 50 respectively.
這是我的 php 代碼。 它正確輸出了前 2 行(產品 A 和 B)的數據,但是當涉及到最后一行(產品 C)時,它復制了產品 B 的數據。請告訴我我的代碼有什么問題? 先感謝您。
$products = $wpdb->get_results("SELECT * FROM wp_products");
foreach($products as $product){
$productID = $product->productID;
$productName = $product->productName;
$orders = $wpdb->get_results("SELECT a.productID, SUM(a.quantity) as totalQuantity, SUM(a.amount) as totalSales FROM a INNER JOIN b ON a.orderID = b.orderID GROUP BY productID");
if(is_null($orders)){
$totalQuantity = 0;
$totalSales = '0.00';
}
foreach($orders as $order){
$totalQuantity = $order->totalQuantity;
$totalSales = $order->totalSales;
}
$orderItem = array(
'productID' => $productID,
'productName' => $productName,
'totalQuantity' => $totalQuantity,
'totalSales' => $totalSales
);
$records[] = $orderItem;
}
快速修復是(只需將WHERE
添加到您的查詢中):
$orders = $wpdb->get_results("SELECT
a.productID,
SUM(a.quantity) as totalQuantity,
SUM(a.amount) as totalSales
FROM a
INNER JOIN b
ON a.orderID = b.orderID
WHERE a.productID = $productID
GROUP BY productID");
但是看看你的片段,我相信你可以將它簡化(替換完整片段):
$records = $wpdb->get_results("SELECT
p.productID,
p.productName,
COALESCE(SUM(a.quantity),0) as totalQuantity,
COALESCE(SUM(a.amount),0) as totalSales
FROM wp_products p
LEFT JOIN a
GROUP BY p.productID");
我不相信您的查詢是正確的。
我沒有看到表名。 嘗試將其更改為:
FROM `tablename` AS a INNER JOIN `othertable` AS b
用表 a 和 b 的名稱交換表名和其他表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.