mysql日期比较不起作用

时间:2015-04-30 21:57:11

标签: mysql

我已阅读线程并搜索其他论坛但没有运气。

我有两个表,AYEAR和SCHEDULE,如图所示

AYEAR

ay    Block Block_start_date    Block_end_date  
1213    4    2012-07-09         2013-05-13
1314    4    2013-07-01         2014-05-09
1415    4   2014-06-23          2015-05-08
1516    4   2015-07-06          2016-05-09
1617    4   2016-04-11          2017-05-01

SCHEDULE

scheduleid    sched_start_date   sched_end_date

59576370      2016-04-11        2016-05-06
...
...
...

我的预定活动是在2016-04-11和2016-05-06之间。我想知道这个时间框架属于哪一年。

我正在运行以下查询

Select ay, scheduleid, sched_start_date, sched_end_date

from schedule, ayear  o

where scheduleid = 59576370

and block = 4

and sched_start_date >= (select max(block_start_date)
                                   from ayear i
                                   where i.block=  o.block
                                   and sched_start_date >= i.block_start_date 
                                   and sched_end_date <= i.block_end_date 
                                   )

and sched_end_date <=  (select max(block_end_date)
                                   from ayear i
                                   where i.block=  o.block
                                   and sched_start_date >= i.block_start_date 
                                   and sched_end_date <= i.block_end_date 
                                   )

它给了我这个:

ay    sched     sched_start_date sched_end_date block_start_date  block_end_dt

1213  59576370  2016-04-11       2016-05-06     2012-07-09        2013-05-13      
1314  59576370  2016-04-11       2016-05-06     2013-07-01        2014-05-09      
1415  59576370  2016-04-11       2016-05-06     2014-06-23        2015-05-08      
1516  59576370  2016-04-11       2016-05-06     2015-07-06        2016-05-09      
1617  59576370  2016-04-11       2016-05-06     2016-04-11        2017-05-01      

当我希望得到最后一行时。

两个表中的所有日期字段都定义为日期。

我想我的问题是,如何确定重叠的时间范围?

1 个答案:

答案 0 :(得分:0)

请考虑以下事项:

CREATE TABLE ayear
(ay    INT NOT NULL PRIMARY KEY
,Block INT NOT NULL
,Block_start_date    DATE NOT NULL
,Block_end_date   DATE NOT NULL
);

INSERT INTO ayear VALUES
(1213    ,4    ,'2012-07-09','2013-05-13'),
(1314    ,4    ,'2013-07-01','2014-05-09'),
(1415    ,4   ,'2014-06-23','2015-05-08'),
(1516    ,4   ,'2015-07-06','2016-05-09'),
(1617    ,4   ,'2016-04-11','2017-05-01');

重叠时间范围的标准模式如下:

SELECT * 
  FROM ayear 
 WHERE '2016-05-06' > block_start_date 
   AND '2016-04-11' < block_end_date;
+------+-------+------------------+----------------+
| ay   | Block | Block_start_date | Block_end_date |
+------+-------+------------------+----------------+
| 1516 |     4 | 2015-07-06       | 2016-05-09     |
| 1617 |     4 | 2016-04-11       | 2017-05-01     |
+------+-------+------------------+----------------+