从多个表中添加总计

时间:2016-10-11 20:14:37

标签: mysql laravel eloquent

我在MySQL上使用Laravel和Eloquent。基本上我试图从发票中获得结果,包括他们的“总额”和“付费”金额。

我有4张桌子:

发票

id int(10),
date_due date,
client_id int(10),
deleted_at datetime

invoices_items

id int(10),
invoice_id int(10),
price decimal(15,2),
quantity int(10)

invoices_payments(这是一个数据透视表,因为付款也可以应用于其他发票)

payment_id int(10),
invoice_id int(10),
amount decimal(15,2)

付款

id int(10),
payment_date date,
total decimal(15,2)

(还有其他字段,但它们不相关)

我一直在使用此查询,基于其他一些答案和其他研究:

select 
    `invoices`.*, 
    SUM(
        invoices_items.price * invoices_items.quantity
    ) as total ,
    SUM(
        invoices_payments.amount
    ) as paid
from 
    `invoices` 
    left join `invoices_items` on `invoices`.`id` = `invoices_items`.`invoice_id` 
    left join `invoices_payments` on `invoices`.`id` = `invoices_payments`.`invoice_id` 
where
    `invoices`.`deleted_at` is null
limit 
    25

我遇到的问题是结果总是只返回1行(测试数据库中有5张发票),“总计”或“付费”的金额不正确。

我想补充一点,invoices_payments

中可能没有任何记录

- 解决方案 -

如果有人遇到类似情况,这是最终查询

select 
    `invoices`.*, 
    COALESCE(SUM(
        invoices_items.price * invoices_items.quantity
    ),0) as total, 
    COALESCE(SUM(invoices_payments.amount),0) as paid, 
    COALESCE(SUM(
        invoices_items.price * invoices_items.quantity
    ),0) - COALESCE(SUM(invoices_payments.amount),0) as balance 
from 
    `invoices` 
    left join `invoices_items` on `invoices`.`id` = `invoices_items`.`invoice_id` 
    left join `invoices_payments` on `invoices`.`id` = `invoices_payments`.`invoice_id` 
where 
    `invoices`.`deleted_at` is null 
group by 
    `invoices`.`id` 
order by 
    `balance` desc 
limit 
    25

1 个答案:

答案 0 :(得分:2)

GROUP BY invoices.id

之后添加WHERE