【问题标题】:Mysql2::Error: Unknown column 'comments' in 'having clause'Mysql2::Error:“有子句”中的未知列“评论”
【发布时间】:2017-08-29 19:39:17
【问题描述】:

在控制器中,我有一个带有子选择的活动查询来获取计数,并希望使用该计数来进一步限制返回的行。例如,cmets = 0

我正在使用有,因为这是我可以在 mysql 提示符下测试它的唯一方法。在 where 子句中检查聚合函数不起作用。

有什么想法吗?

最终,我的目标是将其调整为销毁语句以删除符合该条件的值,但我什至不知道该怎么做。所以这意味着只从 hbookmarks 表中删除行(而不是书签表)。

来自控制器的代码:

Hbookmark.joins("INNER JOIN bookmarks ON hbookmarks.bookmark_id = bookmarks.id")
         .select("bookmarks.short_name, hbookmarks.id, ( select count(*) from clickcomments where clickcomments.click_id = hbookmarks.id ) as comments")
         .where("bookmarks.user_id = ? AND hbookmarks.create_date < DATE_SUB(NOW(), INTERVAL 1 YEAR )", current_user.id)
         .having("comments = 0")
         .order("hbookmarks.create_date desc")

【问题讨论】:

  • 完全不酷,但原始 sql 工作。但是不想用。而是做主动记录。 sql = "select b.short_name, h.create_date, h.id, ( select count(*) from clickcomments c where c.click_id = h.id ) as commentcount from bookmarks b, hbookmarks h where b.user_id=#{current_user.id} and h.bookmark_id = b.id and h.create_date &lt; DATE_SUB(NOW(), INTERVAL 1 YEAR) having commentcount=0 order by h.create_date desc" @topurge = ActiveRecord::Base.connection.execute(sql)
  • 抱歉,用commentcount代替了cmets,这样更清楚
  • 有人用代码清理了,但是有一个调试器行,我将解释它很重要。 logger.info("purge size with no comments: " + @topurge.size.to_s)

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


【解决方案1】:

我之前也遇到过类似的问题,我已经通过将comments 替换为您用来定义它的实际 SQL 段来解决它:

having("( select count(*) from clickcomments where clickcomments.click_id = hbookmarks.id ) = 0")

【讨论】:

  • 嗨,谢谢。当我这样做时,hbookmarks.id 是未知的。( select count(*) from clickcomments where clickcomments.click_id = hbookmarks.id ) 导致 Mysql2::Error: Unknown column 'hw.hbookmarks.id' in 'where clause'
【解决方案2】:

最终它在 ActiveRecord 上的 size 命令上失败了,我在 logger 语句中使用了该命令。

logger.info("purge size with no comments: " + @topurge.size.to_s)

使用 .length 不会导致错误,并且查询的其余部分工作正常。完成后我将 .length 注释掉。

正确的做法是:

logger.info("purge size with no comments: " + @topurge.length.to_s)

至于我的另一个问题,如何直接删除 ActiveRecord 上的 destroy_all。现在我的数据库有几个用户有 1000 行,所以在这种情况下,我进入 mysql 并进行了手术删除,执行速度很快,而这个 activerecord 很慢。是否有人有更好、更快、对性能影响更小的 Rails 中的删除方式,请告诉我。

# remove the old clicks that do not have comments - we'll keep those for search look up
@topurge.destroy_all

【讨论】:

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