今天是两个(DATETIME)列之间的今天? (空或全零计为未绑定的上限/下限)

时间:2012-06-27 15:13:02

标签: mysql

我有一个产品表和两个DATETIME列,一个用于start_date,另一个用于end_date。

如何检查特定产品ID是否在开始日期和结束日期之间?但是,如果其中一个或两个为NULL(默认值),则接受此下限/上限为无限制,如果产品仍在另一个范围内(如果已设置),则返回该产品。如果两个边界都设置为NULL,则始终返回产品。

2 个答案:

答案 0 :(得分:2)

select *
from your_table
where
product_id = 1 AND
(
   (CURDATE() between start_date and end_date) 
   or (CURDATE() >= start_date and end_date is null) 
   or (CURDATE() <= end_date and start_date is null)
   or (start_date is null and end_date is null)
)

答案 1 :(得分:0)

select case when ('2012-06-26' between start_date and end_date) 
                or ('2012-06-26' >= start_date and end_date is null) 
                or ('2012-06-26' <= end_date and start_date is null)
            then 1
            else 0
            end as is_between_dates
from your_table
where product_id = 1