我有2個表,我想合併。我想用相應的總量和總量打印所有產品。mysql查詢 - 顯示使用內部連接的mysql結果的錯誤
這就是我所擁有的。
//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代碼。它能夠正確輸出前兩行(產品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;
}
我對這些產品做了一個foreach循環,然後對每個產品我查詢了它的總數量和銷售量。我用這個代碼:$ orders = $ wpdb-> get_results(「SELECT table_a.productID,SUM(table_a.quantity)as totalQuantity,SUM(able_a.amount)as totalSales FROM table_a INNER JOIN table_b ON table_a.orderID = table_b.orderID GROUP BY productID「);'我得到了正確的值,除了那些假設totalQuantity和totalSales爲0的人。 – user3383911
合併不起作用。我也嘗試了IFNULL,但它運行得並不順利。 – user3383911
你的意思是*不工作*?在我的代碼中根本沒有'able_a.amount','table_a.quantity'和'table_a'。所以儘量做得更精確,並提供精確的表名和表格模式 – Alex