activerecord对所选查询结果的条件

jogvjijk  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(303)
Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
.where("borrowers.type='moulde_b'")
.select(" borrowers.id as id,sum(receivables.amount) as invoice_amount");

从上面的结果集中,我尝试在select语句之后执行where条件。
我在尝试下面的方法,

Borrower.joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id")
    .where("borrowers.type='moulde_b'")
    .select(" borrowers.id as id,sum(receivables.amount) as invoice_amount").where("receivables.amount = 12323.23");

在sum列上选择where条件之后,是否真的可以这样做。

lvjbypge

lvjbypge1#

使用 ActiveRecord::QueryMethods#having 而不是 where :

Borrower.
  joins("INNER JOIN receivables ON receivables.borrower_id = borrowers.id").
  where("borrowers.type = 'moulde_b'").
  select("borrowers.id as id, sum(receivables.amount) as invoice_amount").
  group("borrowers.id"). # mandatory for having
  having("invoice_amount = 12323.33")

链接这些方法的顺序实际上并不重要,因为 AR 会在构建真正的sql查询时重新排列它。

相关问题