我想在Rails 4中加入2個表,以執行計數並保留連接表的列。Rails 4加入GROUP BY和SELECT
模式:用戶的has_many:訂單
我想要什麼:訂單號,最後令的日期。
has_many :orders, -> { select("users.*, count(orders.id) as orders_count").group('users.id') }
我想選擇Orders表created_at列像這樣
select("users.*, orders.created_at, count(orders.id) as orders_count").group('users.id')
但在這種情況下,我得到一個錯誤
PG::GroupingError: ERROR: column "orders.created_at" must appear in the GROUP BY clause or be used in an aggregate function
我需要的第一個created_at所以我在created_at列上嘗試SQL聚合函數「FIRST」
select("users.*, first(orders.created_at) as most_recent, count(orders.id) as orders_count").group('users.id')
但我會得到
PG::UndefinedFunction: ERROR: function first(character varying) does not exist
任何想法,我怎麼能做到這一點JOIN,COUNT並選擇連接表?
你可以發佈你的模型關係,並準確地描述你想要什麼嗎?你想要每個用戶的訂單數量? – Typpex
剛剛編輯問題 –
@stefano_cdn,您正在使用哪個版本的PostgreSQL? –