我有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