避免在三个表之间重复行

时间:2019-11-05 05:46:29

标签: mysql sql left-join

我正在编写一个查询3个表,其中包含一些计算。一张以客户名义列出的表格在表debit_items中可能有一个或多个借方,每个借方在表credit_items中可以有一个或多个贷方。在这里,我应该找到每个客户的总借方和总贷方,但是问题是,如果借方有一个以上的贷方,则该借方将被计算为重复。

客户1借方项目2贷方项目3

我写的查询是这样的:

SELECT customers.*,
       sum(CASE
             WHEN debit_items.customer_id = customers.id THEN
              debit_items.debit_amount
             ELSE
              0
           END) as total_debit,
       sum(CASE
             WHEN credit_items.debit_id = debit_items.id THEN
              credit_items.credit_amount
             ELSE
              0
           END) as total_credit
  FROM customers
  LEFT JOIN debit_items
    ON customers.id = debit_items.customer_id
   AND debit_items.deleted = '0'
  LEFT JOIN credit_items
    ON debit_items.id = credit_items.debit_id
   AND credit_items.deleted = '0'
 GROUP BY customers.id

如果有人帮助我,我会很感激。

2 个答案:

答案 0 :(得分:0)

LEFT JOIN转换为INNER,仅返回完全匹配的内容:

SELECT c.*,
       sum(CASE
             WHEN di.customer_id = c.id THEN
              d.debit_amount
             ELSE
              0
           END) as total_debit,
       sum(CASE
             WHEN ci.debit_id = di.id THEN
              ci.credit_amount
             ELSE
              0
           END) as total_credit
  FROM customers c
  JOIN debit_items di
    ON c.id = di.customer_id
   AND di.deleted = '0'
  JOIN credit_items ci
    ON di.id = ci.debit_id
   AND ci.deleted = '0'
 GROUP BY c.id

答案 1 :(得分:0)

D:\>project>ng server 首先进入group,其credit items基于sum(),然后再加入debit_id表。

debit