按最近的日期选择

时间:2012-04-02 09:07:48

标签: ruby-on-rails date select datediff

我对此查询存在性能问题:

@event = Event.find_by_sql("
    SELECT * FROM `IdeProNew_development`.`events`
    WHERE device_id = #{session[:selected_cam_id]}
    AND data_type = 'image'
    AND created_at BETWEEN CONVERT('#{params[:selected_date].to_time.beginning_of_day}', DATETIME)
    AND CONVERT('#{params[:selected_date].to_time.end_of_day}', DATETIME)
    ORDER BY abs(CONVERT('#{params[:selected_date]}', DATETIME)- created_at) LIMIT 1
").first

我用它来选择“selected_date”最近的事件...... 没关系,但它很慢,因为扫描所有表格(它非常大),并按照所选日期和记录创建日期之间的差异进行排序。

我尝试使用这样的DATEDIFF:

@event = Event.find_by_sql("
    SELECT * FROM `IdeProNew_development`.`events`
    WHERE device_id = #{session[:selected_cam_id]}
    AND data_type = 'image' AND created_at
    BETWEEN CONVERT('#{params[:selected_date].to_time.beginning_of_day}', DATETIME)
    AND CONVERT('#{params[:selected_date].to_time.end_of_day}', DATETIME)
    ORDER BY abs(DATEDIFF(CONVERT('#{params[:selected_date]}', DATETIME), created_at)) LIMIT 1
").first`

但是效果不好(有时给我一个错误的结果)而且它也很慢。

我的错误在哪里?我可以使用某种类型的索引来快速进行此查询吗?

2 个答案:

答案 0 :(得分:1)

为什么不使用活动记录来执行此操作而不是SQL查询? 像这样:

`@event = Event.where(:device_id => session[:selected_cam_id]).
               where(:data_type => 'image').
               where("created_at >= ? AND created_at <= ?",    
                                 params[:selected_date].to_time.beginning_of_day, 
                                 params[:selected_date].to_time.end_of_day).
               order("created_at DESC").first`

我认为它更有效率。

答案 1 :(得分:1)

你也可以尝试这个

     @event = Event.where(:device_id => session[:selected_cam_id])
     .where(:data_type => 'image').to_a
     .select{|i| i.created_at.to_time >= params[:selected_date].to_time.beginning_of_day 
&& i.created_at.to_time <= params[:selected_date].to_time.end_of_day}
.sort{ |x,y| y.created_at  <=> x.created_at}.first