mysql(条令)正在复制计数结果,可能是由于按分组,但无法找出原因

1aaf6o9v  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(270)

我使用条令作为orm层,但是通过在我的数据库工具中放置一个普通的mysql查询,我得到了相同的结果。所以我的问题是:
我有一个发票表,发票\项目和发票\付款表,我想得到的结果是所有的发票,但没有支付或至少没有完全支付。我知道查询应该是几乎正确的,因为它返回了正确数量的项。。。唯一的问题是,它是将数量乘以许多可能连接的行。
所以我现在的问题是:

select  invoice.*, sum(item.amount * item.quantity) as totalDue, 
        sum(payment.amount) as totalPaid 
from invoices as invoice 
    left join invoice_items as item on item.invoice_id = invoice.id 
    left join invoice_payments as payment on payment.invoice_id = invoice.id 
        and payment.status = 'successful' 
where invoice.invoice_number is not null 
and invoice.sent_at is not null 
and invoice.due_date >= '2018-05-15' 
group by invoice.id 
having count(payment.id) = 0 
    or sum(payment.amount) < sum(item.amount * item.quantity) 
order by invoice.issue_date desc, sum(payment.amount) desc;

如您所见,我的select中也有totaldue和totalpaid(它们仅供参考,如果查询正确,应该删除)。
我看到的是金额乘以6(因为它在付款表中有6项)。
所以也许有人能帮我指出正确的方向,它不会对totaldue进行乘法。我在想,这可能是因为没有我的问题,但小组是失败的。

wa7juj8i

wa7juj8i1#

通过在查询中简单地使用distinct,我解决了这个问题。

select invoice.*, sum(distinct(item.amount * item.quantity)) as totalDue, 
        sum(payment.amount) as totalPaid 
from invoices as invoice 
    left join invoice_items as item on item.invoice_id = invoice.id 
    left join invoice_payments as payment on payment.invoice_id = invoice.id 
        and payment.status = 'successful' 
where invoice.invoice_number is not null 
and invoice.sent_at is not null 
and invoice.due_date >= '2018-05-15' 
group by invoice.id 
having count(payment.id) = 0 
    or sum(payment.amount) < sum(distinct(item.amount * item.quantity)) 
order by invoice.issue_date desc, sum(payment.amount) desc;

我要感谢所有花时间重新设计我的问题的人;-)

相关问题