【问题标题】:MYSQL LEFT JOIN INCORRECT RESULT [duplicate]MYSQL LEFT JOIN INCORRECT RESULT [重复]
【发布时间】:2017-12-13 04:42:40
【问题描述】:

我被困了很长时间,无法找到我的查询有什么问题,LEFT JOIN 中的debit column 有问题,下面给出的Query Result image 中显示。我的debit table 的实际值为500MYSQL 查询显示为1500。 我在这里做错了什么。请帮帮我。

这是我的customers table

这是我的cust_credit table

这是我的cust_debit table

MYSQL Query 给出如下

SELECT 
    customers.id as id, 
    customers.cust_name AS customer_name,
    SUM(cust_debit.debit_amount) as debit,
    SUM(cust_credit.credit_amount) as credit,
    (SUM(cust_debit.debit_amount)) - (SUM(cust_credit.credit_amount)) as balance


    FROM customers
  LEFT JOIN  cust_debit  ON customers.id = cust_debit.cust_id
  LEFT JOIN  cust_credit ON customers.id = cust_credit.cust_id


  GROUP BY customers.id
  ORDER BY customers.id

我的Query Result 如下

【问题讨论】:

  • 您正在添加 cust_debit.debit_amount 列,对于客户一,有 3 条记录,价值 500。结果 1500
  • 选择 customers.id 作为 id,customers.cust_name 作为 customer_name,SUM(cust_debit.debit_amount) 作为客户的借方 LEFT JOIN cust_debit ON customers.id = cust_debit.cust_id GROUP BY customers.id ORDER BY customers.id 为什么这样可以正常工作?

标签: mysql database left-join


【解决方案1】:

信用表中有多行,这会在导致问题的组之前产生多行。如果您取出分组依据并选择所有列,您可以看到这一点。

如果您在子加入中进行分组,这个问题就会消失,那么您在分组之前每个客户都有一行。

SELECT 
  customers.id as id, 
  customers.cust_name AS customer_name,
  SUM(cust_debit.debit_amount) as debit,
  SUM(cust_credit.credit_amount) as credit,
  (SUM(cust_debit.debit_amount)) - (SUM(cust_credit.credit_amount)) as balance
FROM customers
LEFT JOIN cust_debit  ON customers.id = cust_debit.cust_id
LEFT JOIN (
  SELECT cust_id, sum(credit_amount) as credit_amount)
  from cust_credit
  group by cust_id
) cust_credit ON customers.id = cust_credit.cust_id
GROUP BY customers.id
ORDER BY customers.id

【讨论】:

  • 还是同样的问题,还是不行... :(请帮帮我!
  • @newbiee 它怎么不工作你的测试数据是什么你的结果是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2013-11-28
  • 1970-01-01
  • 2012-03-27
  • 2018-12-15
  • 2020-05-05
相关资源
最近更新 更多