【发布时间】: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 < 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