MySQL从一个表中选择所有内容,其中包含来自其他2个表的总和

时间:2013-02-16 23:34:50

标签: mysql

我有3张桌子

发票:id,客户

服务:invioce_id,价格

付款:invoice_id,金额

我想要选择所有发票,其中任何服务价格为amountDue,任何付款金额均为每张发票的amountPaid。

例如,如果我有以下行:

发票

id = 1, client = 232
id = 2, client = 535

服务

invoice_id = 1, price = 5.00
invoice_id = 1, price = 10.00
invoice_id = 2, price = 20.00

付款

invoice_id = 1, amount = 7.00
invoice_id = 2, amount = 12.00
invoice_id = 2, amount = 8.00

我希望所有发票行的结果查询类似于:

发票

id = 1, client = 232, amountDue = 15.00, amountPaid = 7.00
id = 2, client = 535, amountDue = 20.00, amountPaid = 20.00

我有这样的查询:

SELECT invoices.*, 
sum(services.price) AS amountDue, 
sum(payments.amount) AS amountPaid 
FROM invoices 
LEFT JOIN services ON services.invoice = invoices.id 
LEFT JOIN payments ON invoices.id = payments.invoice 
GROUP BY invoices.id

但是生成的amountPaid乘以每张发票的服务数量。

有没有办法通过一个查询提取所有数据?

1 个答案:

答案 0 :(得分:0)

您有两个子表,在各自的连接中返回不同的行数。如果您在没有分组/求和的情况下运行查询,最终会得到:

+------+-----------+-------+-----------+--------+
| id   | serviceid | price | paymentid | amount |
+------+-----------+-------+-----------+--------+
|    1 |         1 |  5.00 |         1 |   7.00 |
|    1 |         1 | 10.00 |         1 |   7.00 |
|    2 |         2 | 20.00 |         2 |  12.00 |
|    2 |         2 | 20.00 |         2 |   8.00 |
+------+-----------+-------+-----------+--------+

请注意发票#1的付款金额$ 7和发票#2的服务价格是如何重复的。 MySQL试图通过复制任何表中行数较少的值来填充查询结构产生的“漏洞”。

要使这种查询起作用,您需要使用核心化子查询,以便每个子查询可以自己进行求和,而不受其他表的行数限制的约束:

select invoices.id,
   (select sum(price) from services where services.iid = invoices.id ) AS service_price,
   (select sum(amount) from payments where payments.iid = invoices.id) AS payment_amount
FROM invoices;

产生

+------+---------------+----------------+
| id   | service_price | payment_amount |
+------+---------------+----------------+
|    1 |         15.00 |           7.00 |
|    2 |         20.00 |          20.00 |
+------+---------------+----------------+