我有一个用于管理商店销售的数据库。我正在尝试编写一个查询,以获取每张发票的总费用和支付的总金额。
所有付款都记录在'invoice_payments'表中。发票的总成本是job_price +所有stock_unit项目(产品)。
'发票'表:
invoice_id job_price
000071 100.00
'stock_unit'表:
unit_id price invoice_id
000261 10 000071
000262 10 000071
000263 10 000071
'invoice_payments'表:
payment_id invoice_id amount
000074 000071 100.00
000075 000071 30.00
查询:
SELECT
invoice.invoice_id,
SUM(stock_unit.`sold_price` + invoice.job_price) AS price,
SUM(`invoice_payments`.`amount`) AS paid
FROM invoice
LEFT JOIN stock_unit
ON stock_unit.invoice_id = invoice.invoice_id
LEFT JOIN invoice_payments
ON invoice_payments.invoice_id = invoice.invoice_id
GROUP BY invoice.invoice_id
当只有1个连接时,查询按预期工作,但是当添加2时,它们会相互影响。
在我添加'invoice_payments'之后:
invoice_id paid
000071 130.00
后:
invoice_id price paid
000071 660.00 390.00
它应该是什么:
invoice_id price paid
000071 130.00 130.00
SQL小提琴无法正常工作,但我已在此处设置了一个架构,以便您可以更好地了解我的表:http://sqlfiddle.com/#!9/091a35
我最好有3个单独的查询并加入吗?
答案 0 :(得分:0)
你应该选择e分离的结果而不是计算结果od两者是同一个加入的查询
SELECT t1.invoce_id, t1.price, t2.paid FROM
(
SELECT
invoice.invoice_id AS invoce_id,
SUM(stock_unit.`sold_price` + invoice.job_price) AS price
FROM invoice
LEFT JOIN stock_unit
ON stock_unit.invoice_id = invoice.invoice_id
GROUP BY invoice.invoice_id ) AS t1
LEFT JOIN
(
SELECT
invoice.invoice_id AS invoce_id,
SUM(`invoice_payments`.`amount`) AS paid
FROM invoice
LEFT JOIN invoice_payments
ON invoice_payments.invoice_id = invoice.invoice_id
GROUP BY invoice.invoice_id ) AS t2
ON t1.invoce_id = t2.invoce_id
答案 1 :(得分:0)
感谢Codecademy的Samantha解决这个问题!
第一个联接为每个发票返回多行。金额取决于您的付款金额。
执行第二次加入时,它尝试加入第一张发票的多个结果,这意味着它在一张发票上多次匹配。
要解决此问题,我们使用子查询对第一个连接进行分组,然后将精简结果加入到下一个查询中。
示例:强>
SELECT sub.invoice_id, sub.price, SUM(invoice_payments.amount) AS paid FROM
(SELECT
invoice.invoice_id AS invoice_id,
SUM(stock_unit.sold_price) + invoice.job_price AS price
FROM invoice
LEFT JOIN stock_unit
ON stock_unit.invoice_id = invoice.invoice_id
GROUP BY invoice.invoice_id) AS sub
LEFT JOIN invoice_payments
ON invoice_payments.invoice_id = sub.invoice_id
GROUP BY sub.invoice_id;
这也有效:
SELECT invoice_payments.invoice_id, p.price, SUM(invoice_payments.amount) AS paid
FROM invoice_payments JOIN
(select stock_unit.invoice_id, SUM(sold_price) + invoice.job_price AS price FROM stock_unit join
invoice ON invoice.invoice_id=stock_unit.invoice_id) AS p
ON p.invoice_id = invoice_payments.invoice_id GROUP BY invoice_id;