gpt4 book ai didi

mysql - 从多个表中添加总计

转载 作者:行者123 更新时间:2023-11-29 06:08:19 25 4
gpt4 key购买 nike

我在 MySQL 上使用 Laravel 和 Eloquent。本质上,我试图从发票中获取结果,包括它们的“总计”和“已支付”金额。

我有 4 个表:

发票

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

发票项目

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

最佳答案

WHERE

之后添加 GROUP BY invoices.id

关于mysql - 从多个表中添加总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com