如何在两个日期之间获得结果?

时间:2017-01-19 11:44:41

标签: mysql laravel-5 between

我有两个日期属性已被阻止,如开始日期2017-01-20和2017-01-25结束两天。在这两个日期之间,房产已被封锁。当我搜索除了这两个日期之外的这两个日期,我想得到剩余的日期。

在这里,我试过在MySQL中搜索网络

select `pd`.*, `pa`.*
from `property_details` as `pd` left join
     `property_gallery` as `pg`
     on `pg`.`property_id` = `pd`.`property_id` left join
     `property_preblock_details` as `pbd`
     on `pbd`.`property_id` = `pd`.`property_id` left join
     `property_amenity` as `pa`
     on `pa`.`property_id` = `pd`.`property_id`
 where `pbd`.`start_date` >= '2017-01-20'  and `pbd`.`end_date` <= '2017-01-25'

select pd.* from 
    `property_details` as `pd` left join 
    `property_gallery` as `pg` on `pg`.`property_id` = `pd`.`property_id` 
    left join `property_preblock_details` as `pbd` 
    on `pbd`.`property_id` = `pd`.`property_id` 
    left join `property_amenity` as `pa`
    on `pa`.`property_id` = `pd`.`property_id` 
 where `pbd`.`start_date` NOT BETWEEN CAST('2017-01-20' AS DATE) and CAST('2017-01-25' AS DATE) 
 AND `pbd`.`end_date` NOT BETWEEN CAST('2017-01-20' AS DATE) and CAST('2017-01-25' AS DATE)

但是我在日期之间得到了结果。

我不想在日期结果之间得到,我想不要在日期结果之间得到。

Property_rate

id    start_date    end_date     prop_id
1     2017-01-20    2017-01-25     1
2     2017-01-26    2017-01-27     1
3     2017-01-26    2017-01-28     2

属性

prop_id  prop_name
1        test1
2        test2

如果我选择2017-01-20和2017-01-25,我想得到&#39; test2&#39;仅限房产详情。不是&#39; test1&#39;的信息。

2 个答案:

答案 0 :(得分:0)

你非常接近。您的查询说明了这一点:

    where `pbd`.`start_date` >= '2017-01-20'   /* close, but wrong */
      and `pbd`.`end_date` <= '2017-01-25'

你想要的是这个:

    where (    `pbd`.`start_date` < '2017-01-20'  
           or  `pbd`.`end_date`  > '2017-01-25')

也可以写

    where not (      `pbd`.`start_date` >= '2017-01-20' 
                 and `pbd`.`end_date` <= '2017-01-25')

请注意您的查询可能还有其他错误。如果您的start_dateend_date列中包含DATE数据类型,那么您已全部设置完毕。但是,如果他们有其他数据类型,例如DATETIMETIMESTAMP,则您的查询还有其他问题。要在2017年1月20日至2017年1月25日期间捕获包含日期/时间值的所有行,您需要这个

where `pbd`.`start_date` >= '2017-01-20'   /*dates IN range */
  and `pbd`.`end_date` < '2017-01-26'

注意我在一天后移动了所需的结束日期,并使用<代替<=。这适用于

          2017-01-25 23:59     should be in range
          2017-01-26 00:00     should be out of range
          2017-01-26 00:01     should be out of range

答案 1 :(得分:0)

尝试:

SELECT * 
FROM  `Table` 
WHERE  `DATECOLUMN` NOT 
IN (

SELECT  'ID'
FROM  `Table` 
WHERE  `DATECOLUMN` 
BETWEEN (
'2017-02-10 00:00:00'
)
AND (
'2017-09-14 00:00:00'
)
)
LIMIT 0 , 30