我使用doctrine作为ORM层,但通过在数据库工具中放置一个简单的mysql查询,我得到了相同的结果。所以我的问题是:
我有一个invoices表、invoice\u items和invoice\u payments表,我希望得到的结果是所有尚未支付或至少尚未全额支付的发票。我知道这个查询应该是几乎正确的,因为它返回了正确数量的项目。。。唯一的问题是,它将数量乘以许多可能连接的行。
所以我现在的问题是:
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项)。
所以也许有人可以帮我指出正确的方向,它不会对总到期日进行乘法运算。我在想,这可能是因为没有我提问的小组失败了。