我有一个Payment
5 行的模型。其中 4 个具有相同的 user_id 和一个不同的。我尝试按 user_id 对这些结果进行分组。它应该返回两个结果,但是在尝试这个时我总是得到五个结果。知道为什么吗?
(我正在使用 Postgres)
Payment.find(:all, group: "user_id,id").count
=> 5
也试过
Payment.find(:all, group: "id,user_id").count
=> 5
更新:如果我不添加“user_id”,我会收到此错误
ActiveRecord::StatementInvalid: PG::Error: ERROR: column "payments.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "payments".* FROM "payments" GROUP BY user_id
^
: SELECT "payments".* FROM "payments" GROUP BY user_id
更新 2:此查询
Payment.joins(:user).select('payments.id,users.username,payments.user_id,payments.token,payments.period_start_at,payments.amount_cents,payments.currency').group("user_id")
返回PG::Error: ERROR: column "payments.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT payments.id,users.username,payments.user_id,payments....
^
如果我将“payments.id”添加到组子句中,它将不会按 user_id 对它们进行分组。任何想法?