如何在mysql中优化这三个表查询?

时间:2016-02-20 17:43:57

标签: mysql

please click to see the image to help make query

customer
cus_ID  name
1       jon
2      maik

order
rec_ID  cus_ID  amount
1         1      100
2         1      100
3         1      100
4         1      100
5         2      150
6         2       50

payment
pay_ID  cus_ID  amount
1          1    100
2          1    100
3          1    50
4          2    50

OUTPUT Need

name    order_amount    pay_amount
jon         400           250
maik        200            50

这是我的三个表如何在mysql查询中获得输出。我会试试这段代码

SELECT c.name
     , SUM(o.amount) oamount
     , SUM(p.amount) pamount 
  FROM customer c
  JOIN `order` o 
    ON o.cus_ID = c.cus_ID
  JOIN payment p 
    ON p.cus_ID = c.cus_ID 
 GROUP 
    BY c.cus_ID

但是没有做出完美的结果请帮助解决这个问题

1 个答案:

答案 0 :(得分:2)

由于您正在处理所有客户,并且为了防止每个订单/付款表中的记录多于另一个表的假笛卡尔产品,请仅根据客户ID创建每个分组的SUBQUERIES联接。

我已经对子查询进行了LEFT-JOIN .JUST IN CASE有条目没有付款或没有订单阻止记录被包括在内。不需要最终组,因为每个客户记录只有一个,并且由于基础子查询也按客户ID分组,因此每个子查询最多只能有一条记录,并且永远不会产生笛卡尔集。

SELECT 
      customer.name, 
      COALESCE( sumOrder.TotalOrders, 0 ) AS oamount, 
      COALESCE( sumPay.TotalPay, 0 ) AS pamount 
   FROM 
      customer 
         LEFT JOIN 
         ( select o.cus_id,
                  sum( o.amount ) as TotalOrders
              from 
                 order o 
              group by
                 o.cus_id ) sumOrder
            ON customer.cus_ID = sumOrder.cus_ID 
         LEFT JOIN 
         ( select p.cus_id,
                  sum( p.amount ) as TotalPay
              from 
                 payment p
              group by
                 p.cus_id ) sumPay
            ON customer.cus_ID = sumPay.cus_ID