2016-05-31 21 views
-1

私はマージしたい2つのテーブルを持っています。私はすべての製品を対応する総量と総量で印刷したいと思います。mysql query - 内部結合を使用してmysql結果を表示するエラー

これは私が持っているものです。私はここでは、この

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. 

をやりたい

//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    

は私の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; 
} 

答えて

0

私はあなたの質問が正しいとは思わない。

テーブル名が表示されません。

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

表aと表bの名前を持つ表名と他の表を交換してください。

1

クイック修正が(ちょうどあなたのクエリにWHEREを追加)です。

$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

$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"); 

しかし、あなたのフラグメントを見て、私は(フルフラグメントを置き換える)にあなたがそれを簡略化することができると信じて私は製品のforeachループを行い、次にすべての製品について、その総量と売上を照会しました。私はこのコードを使って、$ orders = $ wpdb-> get_results( "total 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

Coalesceが機能していません。私はIFNULLも試みましたが、うまくいきません。 – user3383911

+0

*働いていないことはどういう意味ですか?私のコードには 'able_a.amount'も' table_a.quantity'も 'table_a'もありません。だから、より正確にしようと正確なテーブル名とテーブルのスキーマを提供する – Alex

関連する問題