0

我想将在搜索字段中输入的日期(例如 04.07.2012)与我表中的日期(datetime名为 的列date)进行比较。但是,我似乎无法直接获得我的 SQL 查询。

我尝试了什么:

find(:all, :conditions => ['\'to_timestamp(date, \'DD Mon YYYY\')\' LIKE \'to_timestamp(?, \'DD Mon YYYY\')\'', '#{query}']) 

但它失败了:

PG::Error: ERROR:  syntax error at or near "DD"
LINE 1: ...s".* FROM "projects"  WHERE ('to_timestamp(date, 'DD Mon YYY...
                                                             ^
: SELECT "pacients".* FROM "projects"  WHERE ('to_timestamp(date, 'DD Mon YYYY')' LIKE 'to_timestamp('#{query}', 'DD Mon YYYY')')

就(postgre)SQL 而言,我是一个真正的新手,我真的很感激在编写这个查询的正确方向上的一些提示。

太感谢了!

4

1 回答 1

3

As meager pointed out there are a couple of issues here:

  • incorrect string interpolation
  • making the database do more work than necessary and using LIKE when you can do date searching more directly:

Let ActiveRecord format the date inputs use straight SQL to compare the dates, something like:

start_date = Date.civil(2012, 7, 4)
end_date = Date.civil(2012, 7, 20)
User.where(["date BETWEEN ? AND ?", start_date, end_date])

Converting the source date and the dates in the database to a timestamp formatted like a string and then using LIKE is very round-about and poor performing as well.

于 2012-07-04T18:09:27.353 回答