Mysql离开了join和sum

时间:2013-05-02 11:03:30

标签: mysql sum left-join

我有三张桌子,我需要额外的金额。此外,我将使用select或where子句中的字段。

SELECT i.*, x.* FROM items AS i 
 LEFT JOIN
 (
   SELECT
   p.item_id
   ,SUM(p.amount) AS saleAmount
   ,SUM(IF(p.type=1,pa.amount,0)) AS paidAmount
   FROM payments AS p
   LEFT JOIN payment_actions AS pa ON pa.payment_id=p.id
   GROUP BY p.id
) AS x ON x.item_id=i.id

项目表;

id  
---
1

付款表;

id  |   item_id |   amount
---------------------------
1   |   1       |   300 

payment_actions表;

id  |   payment_id  |   amount
---------------------------
1   |   1           |   100 
1   |   1           |   50

结果应该是;

saleAmount  | paidAmount
--------------------------
    300     |   150

1 个答案:

答案 0 :(得分:14)

这是获得理想结果的简便方法

SELECT
  i.id,
  p.amount,
  pa.amount
FROM items AS i
  LEFT JOIN (SELECT
           id,
           item_id,
           SUM(amount)    amount
         FROM payments
         GROUP BY item_id) AS p
    ON p.item_id = i.id
  LEFT JOIN (SELECT
           payment_id,
           sUM(amount)    amount
         FROM payment_actions) AS pa
    ON pa.payment_id = p.id
group by i.id