[英]Retrieve all records that occur within specific date range in MySQL
I have a table that contains several contracts, and each contract has a start date and an end date, like this:我有一个包含多个合同的表,每个合同都有一个开始日期和一个结束日期,如下所示:
| ID | Contract Name | Start Date | End Date |
|-------|-------------------|--------------|------------|
| 1 | Joe Bloggs | 2012-01-01 | 2012-02-05 |
| 2 | John Smiths | 2012-02-01 | 2012-02-20 |
| 3 | Johnny Briggs | 2012-03-01 | 2012-03-20 |
What I am trying to do is build a query that will retrieve contracts that were active between a specific time period.我想要做的是构建一个查询,该查询将检索在特定时间段之间处于活动状态的合同。 So if I had the start date of
2012-02-10
and an end date of 2012-03-21
I should have the following contracts displayed:因此,如果我的开始日期为
2012-02-10
,结束日期为2012-03-21
我应该显示以下合同:
| ID | Contract Name | Start Date | End Date |
|-------|-------------------|--------------|------------|
| 2 | John Smiths | 2012-02-01 | 2012-02-20 |
| 3 | Johnny Briggs | 2012-03-01 | 2012-03-20 |
My problem though is that I don't know how to build the query to do this.我的问题是我不知道如何构建查询来做到这一点。 This is what I've got so far:
这是我到目前为止所得到的:
SELECT *
FROM contracts c
WHERE c.startdate BETWEEN '2012-02-10'
AND '2012-03-21'
AND c.enddate BETWEEN '2012-02-10'
AND '2012-03-21'
This doesn't work though, no records are retrieved.但这不起作用,没有检索到任何记录。 What am I doing wrong?
我究竟做错了什么?
SELECT * FROM contracts
WHERE (START_DATE between '2012-03-01' AND '2013-03-21')
OR (END_DATE between '2012-03-01' AND '2013-03-21')
OR (START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21');
Er, time is linear right?呃,时间是线性的吧?
SELECT *
FROM contracts
WHERE end_date >= '2012-02-10'
AND start_date <= '2012-03-21';
Let me illustrate...让我举例说明...
A-------------B
<------->
<------>
<----------->
<---------------------->
In all cases above, the start date is less than B. The end date is greater than A.在上述所有情况下,开始日期都小于 B。结束日期大于 A。
对我来说,一个好的要求是
SELECT * FROM contracts c WHERE c.startdate >'2012-02-10' AND c.enddate < '2012-03-21'
It should have been like this本来应该是这样的
SELECT *
FROM contracts c
WHERE c.startdate >= '2012-02-10'
AND c.enddate <= '2012-03-21'
SELECT * FROM contracts
WHERE
(START_DATE between '2012-03-01' AND '2013-03-21')
OR (END_DATE between '2012-03-01' AND '2013-03-21')
OR (START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21');
explanation:解释:
(START_DATE between '2012-03-01' AND '2013-03-21')
: intervals records that start between the input dates. : 在输入日期之间开始的间隔记录。 First part or all of interval might be included.
可能包括区间的第一部分或全部。
(END_DATE between '2012-03-01' AND '2013-03-21')
: intervals that end between the input dates. : 在输入日期之间结束的间隔。 Last part or all of interval might be included.
可能包括间隔的最后一部分或全部。
(START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21')
: input dates are included within one interval only : 输入日期只包含在一个间隔内
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.