以下查询
SELECT
invoices.id,
SUM(payments.amount)
FROM adass.invoices
INNER JOIN adass.payments ON invoices.id=payments.id_invoice
GROUP BY invoices.id ORDER BY 1 desc LIMIT 0, 25
返回以下结果
但是,当我将另一个表连接到查询时:
SELECT
invoices.id,
SUM(payments.amount)
FROM adass.invoices
INNER JOIN adass.invoice_items ON invoices.id=invoice_items.id_invoice
INNER JOIN adass.payments ON invoices.id=payments.id_invoice
GROUP BY invoices.id ORDER BY 1 desc LIMIT 0, 25
它复制了发票ID 13919的付款金额,有效地将表中的100付款加倍
造成这种情况的原因是什么?
我添加了下面的表格内容
更新:更大的查询如下
SELECT SQL_CALC_FOUND_ROWS invoices.id,
COALESCE(SUM(invoice_items.gross),0) AS gross,
COALESCE(SUM(invoice_items.net) - SUM(invoice_items.gross),0) AS vat,
COALESCE(SUM(invoice_items.net),0) AS net,
COALESCE(SUM(payments.amount),0),
COALESCE(SUM(payments.amount) - SUM(invoice_items.net),0) AS outstanding
FROM adass.invoices
LEFT JOIN adass.invoice_items ON invoices.id=invoice_items.id_invoice
LEFT JOIN adass.payments ON invoices.id=payments.id_invoice
GROUP BY invoices.id ORDER BY 1 desc LIMIT 0, 25
答案 0 :(得分:0)
很清楚发生了什么。您的INVOICE#13919有两个发票项目,因此您获得双发票金额,因为您的查询生成了两行。如果您有三个发票项目,那么金额将增加两倍。
您需要从查询INNER JOIN adass.invoice_items ON invoices.id=invoice_items.id_invoice
中删除此子句,因为您还没有使用adass.invoice_items
中的列。
您的查询将是:
SELECT invoices.id,
SUM(payments.amount)
FROM adass.invoices
INNER JOIN adass.payments ON invoices.id=payments.id_invoice
GROUP BY invoices.id ORDER BY 1 desc LIMIT 0, 25