内连接和左连接在mysql中没有按预期工作

时间:2016-11-27 08:39:33

标签: mysql

我有3张桌子

table_supplier_bills - bill_id, supplier_id, date
table_supplier_bill_details - bill_id, product_id, quantity, rate
table_supplier_bill_payment_details - id, bill_id, payment_date, amount

我希望用bill_amount和paid_amount获得所有账单。

这是我的疑问。

select 
SB.bill_id, 
SB.date, SB.supplier_id, 
SUM(SBD.quantity * SBD.rate) as bill_amount, 
COALESCE(SUM(SBPD.payment_amount), 0.00) as paid_amount 
from table_supplier_bills SB 
INNER JOIN 
table_supplier_bill_details SBD 
ON SB.bill_id = SBD.bill_id 
LEFT JOIN table_supplier_bill_payment_details SBPD 
ON SBD.bill_id = SBPD.bill_id 
group by SBD.bill_id;

但是如果账单的table_supplier_bill_details中有多行,则此查询不会给出正确的paid_amount。在多行查询的情况下,给出paid_amount乘以该表的table_supplier_bill_details中的行数。

有人可以帮我解决这里的错误吗?

1 个答案:

答案 0 :(得分:2)

改为使用相关查询:

SELECT SB.bill_id, 
       SB.date,
       SB.supplier_id, 
       SUM(SBD.quantity * SBD.rate) as bill_amount, 
       COALESCE((SELECT SUM(SBPD.payment_amount)
                 FROM table_supplier_bill_payment_details SBPD 
                 WHERE SBD.bill_id = SBPD.bill_id ),0.00) as paid_amount 
FROM table_supplier_bills SB 
INNER JOIN table_supplier_bill_details SBD 
 ON SB.bill_id = SBD.bill_id
GROUP BY SBD.bill_id;