2016-05-31 55 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