0
如何爲以下MySQL查詢編寫rails4活動記錄等效查詢?SQL查詢的Rails等效活動記錄查詢
SELECT c.id,c.account_name,sum(i.balance) as balance from clients c, invoices i
where c.id = i.client_id GROUP BY c.id
如何爲以下MySQL查詢編寫rails4活動記錄等效查詢?SQL查詢的Rails等效活動記錄查詢
SELECT c.id,c.account_name,sum(i.balance) as balance from clients c, invoices i
where c.id = i.client_id GROUP BY c.id
Client.joins(:invoices).select('clients.id, clients.account_name, sum(invoices.balance) as balance').group('clients.id')
是否有可能寫出來與聯接查詢? – Vasu
'Client.joins(:invoices)'相當於'from clients c,invoices i where c.id = i.client_id'。 –
但您也可以使用'find_by_sql'方法:'Clients.find_by_sql「SELECT c.id,c.account_name,sum(i.balance)作爲客戶端餘額c,發票i其中c.id = i.client_id GROUP BY c.id「'應該工作。 –