2016-05-31 96 views
-1

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

回答

0

我不相信你的查詢是正確的。

我沒有看到表名。嘗試將其更改爲:

FROM `tablename` AS a INNER JOIN `othertable` AS b 

使用表a和b的名稱替換表名和其他表。

1

快速的修復(剛加入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"); 
+0

我對這些產品做了一個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

+0

合併不起作用。我也嘗試了IFNULL,但它運行得並不順利。 – user3383911

+0

你的意思是*不工作*?在我的代碼中根本沒有'able_a.amount','table_a.quantity'和'table_a'。所以儘量做得更精確,並提供精確的表名和表格模式 – Alex