问题描述
我有以下查询:
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15).uniq
并给我错误
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...s"."user_id" WHERE (articles.user_id != 1) ORDER BY Random() L...
当我更新原始查询到
Article.joins(:themes => [:users]).where(["articles.user_id != ?", current_user.id]).order("Random()").limit(15)#.uniq
所以错误消失了......在 MySQL .uniq 中有效,在 PostgreSQL 中没有.有没有其他选择?
so the error is gone... In MySQL .uniq works, in PostgreSQL not. Exist any alternative?
推荐答案
如错误所述for SELECT DISTINCT, ORDER BY 表达式必须出现在选择列表中
.因此,您必须显式选择您正在排序的子句.
As the error states for SELECT DISTINCT, ORDER BY expressions must appear in select list
.Therefore, you must explicitly select for the clause you are ordering by.
这是一个例子,它与您的情况类似,但稍微概括一下.
Here is an example, it is similar to your case but generalize a bit.
Article.select('articles.*, RANDOM()')
.joins(:users)
.where(:column => 'whatever')
.order('Random()')
.uniq
.limit(15)
因此,使用 .select()
显式包含您的 ORDER BY
子句(在本例中为 RANDOM()
).如上所示,为了让您的查询返回文章属性,您还必须明确选择它们.
So, explicitly include your ORDER BY
clause (in this case RANDOM()
) using .select()
. As shown above, in order for your query to return the Article attributes, you must explicitly select them also.
我希望这会有所帮助;祝你好运
I hope this helps; good luck
这篇关于Rails 3、ActiveRecord、PostgreSQL - “.uniq"命令不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!