我在将此SQL语句转换为activerecord / ruby友好代码时遇到问题。请注意,end_at日期实际上是DateTime.now。
SELECT DISTINCT events.id FROM events, channels
WHERE events.channel_id = channels.id AND events.end_at >= '2015-02-11 22:55:04'
ORDER BY start_at ASC, id ASC LIMIT 40
建议?
编辑:这个问题的最初起源是因为mysql不支持我正在处理的应用程序的子查询中的嵌套限制。所以分页+此查询导致错误:
# channels is an activerecord relation, order_by_schedule is a scope
Event.where(:channel_id => channels).where{ end_at >= DateTime.now }.order_by_schedule.limit(channels.count * event_limit)
答案 0 :(得分:0)
我认为您不需要加入channels
,因为您根本不使用它们:
Event.select('DISTINCT id')
where('end_at >= NOW()').
order('started_at, id').
limit(40)