【问题标题】:Mysql2::Error: Unknown column 'ctr' in 'having clause'Mysql2::Error:“有子句”中的未知列“ctr”
【发布时间】:2012-11-24 04:54:13
【问题描述】:

我遇到了类似的错误

Mysql2::Error: Unknown column 'ctr' in 'having clause': SELECT COUNT(*) AS count_all, artists.id AS artists_id FROM `artists` INNER JOIN `photos` ON `photos`.`photoable_id` = `artists`.`id` AND `photos`.`photoable_type` = 'Artist' WHERE (admin_approved = 1) GROUP BY artists.id HAVING ctr >= 2

我的艺术家模型我写范围

scope :approved, where("admin_approved = ?", true)
scope :completed_profile, joins(:photos).select("artists.*,count(photos.id) as ctr").group("artists.id").having("ctr >= 2")

在我的控制器中我写

  def artists_completed_profile
     @artists = Artist.approved.completed_profile.page(params[:page]).per(10)
     @total_artists = @artists.size
  end 

注意:当我在控制台中尝试时,我没有收到任何错误,但是当我在模型或控制器中写入时,我会收到此错误。

提前致谢

【问题讨论】:

  • 你的服务器运行在什么模式下?
  • 再次运行迁移。如果失败,请重新启动您的网络服务器。

标签: mysql ruby-on-rails ruby-on-rails-3.2 rails-activerecord


【解决方案1】:

您的分页中的某些内容正在执行.count,这很可能是在它试图计算匹配总数以及总页数时。 .count 将忽略您范围的 .select 部分,这就是您看到的原因:

SELECT COUNT(*) AS count_all, artists.id AS artists_id ...

正在发送到 MySQL。您的ctr 别名由您的.select 定义,因此.count 的SQL 失败。您应该可以通过在 HAVING 中不使用 ctr 来解决此问题,只需使用原始的 count(photos.id)

scope :completed_profile, ...having("count(photos.id) >= 2")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2016-05-11
    • 2020-05-14
    • 2019-05-07
    相关资源
    最近更新 更多