这适用于SQLite3,但不适用于PostgreSQL。
我得到的错误是PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
我正在尝试使用代码显示exercises
中的所有group
:current_user.group.exercises
这是关系
一个小组有很多锻炼,锻炼有很多练习
在我的群组模型中,我有has_many :exercises, through: :workouts
有什么想法吗?
编辑1:
这是SQL rails正在生成:
SELECT DISTINCT "exercises".*
FROM "exercises"
INNER JOIN "workout_exercises" ON "exercises"."id" = "workout_exercises"."exercise_id"
INNER JOIN "workouts" ON "workout_exercises"."workout_id" = "workouts"."id"
INNER JOIN "groups_workouts" ON "workouts"."id" = "groups_workouts"."workout_id"
WHERE "groups_workouts"."group_id" = 2
ORDER BY exercise_order, workout_order
这是错误:
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ..." WHERE "groups_workouts"."group_id" = 2 ORDER BY exercise_o...
^
: SELECT DISTINCT "exercises".* FROM "exercises" INNER JOIN "workout_exercises" ON "exercises"."id" = "workout_exercises"."exercise_id" INNER JOIN "workouts" ON "workout_exercises"."workout_id" = "workouts"."id" INNER JOIN "groups_workouts" ON "workouts"."id" = "groups_workouts"."workout_id" WHERE "groups_workouts"."group_id" = 2 ORDER BY exercise_order, workout_order
答案 0 :(得分:3)
所以这是一个uniq
约束异常。在模型上,我有has_many :exercises, through: :workouts, uniq: true
,Postgres不喜欢。
要修复错误,我将uniq
约束从模型移动到实际查询。所以在这种情况下,我刚做current_user.group.exercises.uniq
这只能解决我的问题。在某些情况下,我希望在模型级别有一个uniq约束,但我还没有找到一种方法来做到这一点。
答案 1 :(得分:1)
每个SQL变体的规则与它接受的表达式略有不同。例如,有关此问题的信息,请参阅Simulating MySQL's ORDER BY FIELD() in Postgresql和相关链接。如果你给出了你正在生成的SQL的细节,你可能会得到更具体的建议。