mysql查询 - 使用内部联接显示mysql结果的错误

时间:2016-05-31 16:20:40

标签: php mysql xampp inner-join

我有2个表要合并。我想打印所有产品及其相应的总数量和总金额。

这就是我所拥有的。

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

2 个答案:

答案 0 :(得分:1)

快速修复(只需在查询中添加class String include MyModule::Utils::Slug end ):

include Hanami::Repository

但是看一下你的片段,我相信你可以简化它(替换完整片段)到:

WHERE

答案 1 :(得分:0)

我认为您的查询不正确。

我没有看到表名。尝试将其更改为:

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

使用表a和b的名称交换tablename和其他表。