我们的数据库中有Payment
(id,total)和Transaction
(payment_id,amount)表(简化为帖子)。付款的ID在交易中,如果需要,可以将它们连接在一起。
以下是我们提出的SQL(稍微简化):
SELECT * FROM payments a WHERE ABS(a.total) <> (SELECT SUM(d.amount) FROM transactions d WHERE a.id = d.payment_id GROUP BY d.payment_id)
我需要为上面的SQL组装一个Rails(4.2)查询,但仍然坚持SELECT sum(d.amount) FROM transactions d WHERE a.id = d.payment_id GROUP BY d.payment_id
有人可以帮忙吗?
答案 0 :(得分:1)
您可以这样翻译:
subquery = Transaction.where("transactions.payment_id = payments.id").group(:payment_id).select("SUM(d.amount)").to_sql
Payment.where("ABS(total) <> (#{subquery}))
答案 1 :(得分:1)
我不是在做子查询,而是在两个表中加入和组合:
Payment.joins(:transactions).
group(:id).
having("ABS(payments.total) <> SUM(transactions.amount)")
这取决于付款和交易之间的以下关联:
Payment < ActiveRecord::Base
has_many :transactions
end