在Left中通过始终从关系表中获取第一个数据来连接订单。 (导轨)

时间:2014-04-24 12:20:43

标签: mysql ruby-on-rails ruby-on-rails-3 sql-order-by left-join

我有两张表,如发票和收据

1. invoices

    id name    amt   status
    1   test    100   paid
    2   test1   300  not paid
    3   test2   400  not paid

2. receipts
    id amount invoice_id receipt_date
     1  50      1         22-apr-2014  
     2  30      1         24-apr-2014   
     3  30      1         25-apr-2014

以下是我的查询

@invoices_info = Invoice.select("invoices.id as inv_id,receipts.receipt_date as receipt_date,sum(receipts.amount) as receipt_amount")
                      .joins('left join receipts on receipts.invoice_id = invoices.id')
                      .where("invoices.status in ('Paid')")
                      .group("invoices.id").order("receipts.receipt_date desc")

This query shows data as:
 inv_id  receipt_amount receipt_date
   1      100            22-apr-2014

问题是,它获取第一个日期而不是降序日期。我想要上次收到日期“25-apr-2014”。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您的Invoice.select()没有映射到有效的SQL。有效的SQL要求SELECT子句中的每个未聚合列也出现在GROUP BY子句中。 MySQL"扩展"到GROUP BY,它允许你所做的,不是确定性的。 (MySQL为您提供了最容易获取的日期。)SQL开发人员认为这是一个错误,而不是一个功能。

我将在本答案的其余部分使用SQL。

在PostgreSQL中执行此SQL语句。 。

select invoices.id as inv_id, receipts.receipt_date as receipt_date, sum(receipts.amount) as receipt_amount
from invoices
left join receipts on receipts.invoice_id = invoices.id
where invoices.status in ('paid')
group by invoices.id, receipts.receipt_date
order by receipts.receipt_date desc

返回此输出。

1   2014-04-24   30
1   2014-04-22   80

如果您只想要每张发票的金额,这更有意义,您可以使用更简单的SQL查询。

select invoice_id, sum(amount)
from receipts
group by invoice_id;

1    110

如果您想要最新收据的总和和日期。 。

select invoice_id, max(receipt_date), sum(amount)
from receipts
group by invoice_id;

1   2014-04-24   110