【发布时间】:2013-08-22 00:59:52
【问题描述】:
我有以下标签方法,它根据标签的使用次数选择标签,然后按该顺序排列它们。代码基于 railscasts 剧集:http://railscasts.com/episodes/382-tagging。
我将我的数据库从以前工作的 mysql 更改为 postgres,您可以在其中看到堆栈跟踪中产生的错误消息。
如何重构此 sql 以使用 postgresql?
def tags
Tag.joins(:taggings).select('tags.*, count(tag_id) as "tag_count"').group(:tag_id).order('tag_count desc')
end
堆栈跟踪
ActiveRecord::StatementInvalid - PG::GroupingError: ERROR: column "tags.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT tags.*, count(tag_id) as "tag_count" FROM "tags" INNE...
^
: SELECT tags.*, count(tag_id) as "tag_count" FROM "tags" INNER JOIN "taggings" ON "taggings"."tag_id" = "tags"."id" GROUP BY tag_id ORDER BY tag_count desc:
标签.rb
class Tag < ActiveRecord::Base
has_many :taggings
has_many :questions, through: :taggings
#omitted for brevity
tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :question
end
如果有人需要更多代码,请大声疾呼。
【问题讨论】:
-
在此处搜索“必须出现在 GROUP BY 子句中或在聚合函数中使用”应该可以找到所需的答案。
-
你是对的,答案就在问题中。
标签: sql ruby-on-rails ruby-on-rails-3 postgresql