Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

ruby on rails 3 - How do I match an entire day to a datetime field?

I have a table for matches. The table has a column named matchdate, which is a datetime field.

If I have 3 matches on 2011-12-01:

  • 2011-12-01 12:00:00
  • 2011-12-01 13:25:00
  • 2011-12-01 16:00:00

How do I query that? How do I query all matches on 1 single date?

I have looked at date_trunc(), to_char(), etc.
Isn't there some "select * where datetime in date" function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cast your timestamp value to date if you want simple syntax. Like this:

SELECT *
FROM   tbl
WHERE  timestamp_col::date = '2011-12-01';  -- date literal

However, with big tables this will be faster:

SELECT *
FROM   tbl
WHERE  timestamp_col >= '2011-12-01 0:0'    -- timestamp literal
AND    timestamp_col <  '2011-12-02 0:0';

Reason: the second query does not have to transform every single value in the table and can utilize a simple index on the timestamp column. The expression is sargable.

Note excluded the upper bound (< instead of <=) for a correct selection.
You can make up for that by creating an index on an expression like this:

CREATE INDEX tbl_ts_date_idx ON tbl (cast(timestamp_col AS date));

Then the first version of the query will be as fast as it gets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...