SQL 'overlaps' only get dates between start and end (not include start and end dates)
I use this query to get objects overlaps the period between "start_date" and "end_date", moreover, I would like get the objects with dates end on start_date and objects begin on end_date.
I use
where("(start_date, end_date) overlaps (date ?, date ?), start_date, end_date"
But the objects has dates <=start_date or >=end_date is not get.
This 'overlaps' only gets objects has dates start_date< dates< end_date, not "=".
For example, start_date='2011/2/1', end_date='2011/3/31'. objects has date ends on '2011/2/1' or start on '2011/3/31' will not be get, only dates between '2011/2/1' and '2011/3/31' will get. how to includes objects which holds date ends on the start_date and start on the end_开发者_开发百科date?
----------------------Edit----------------------------
I try to use:
where("(start_date, end_date) overlaps (date ?, date ?), start_date-1.day, end_date+1.day"
to solve the issue, but when I do like above, if start_date='2011/2/1', end_date='2011/3/31', then objects holds '2011/1/31' also returns which is supposed should not be get.
On the SQL side, you want to generate something like this, assuming
- S1, E1 are the start and end dates of the first range,
- S2, E2 are the start and end dates of the second range,
none of S1, E1, S2, E2 are NULL
WHERE (S1, E1) OVERLAPS (S2, E2) OR (E1 = S2) OR (E2 = S1)
You need both "OR" clauses, because in the general case you don't know which range is earlier.
try this:
where("start_date >= ? and end_date <= ?", start_date.beginning_of_day, end_date.end_of_day)
that should include all from start_date to end_date ;-) hope it helps!
Just assuming a table Details and having attributes(including date),suppose i want info from two specific dates as from start_date to end_date.
so, Details.where(["date between ? and ? ",start_date,end_date]) will give the required info including start and end dates.Hope it helps
精彩评论