Mysql日期范围查询返回错误的结果集

时间:2016-05-27 17:49:48

标签: php mysql date select join

以下是查询:

SELECT `mainevents`.`maineventid`   AS `MainEventID`, 
       `mainevents`.`maineventcode` AS `MainEventCode`, 
       `mainevents`.`datestart`     AS `DateStart`, 
       `mainevents`.`dateend`       AS `DateEnd`, 
       `mainevents`.`location`      AS `Location`, 
       `mainevents`.`name`          AS `Name` 
FROM   `mainevents`, 
       `mainevents_lookup` 
WHERE  `mainevents`.`maineventid` = `mainevents_lookup`.`maineventid` 
       AND `mainevents`.`categoryid` = 1 
       AND ( ( `mainevents_lookup`.`datestart` >= '2016-02-27 00:00:00' 
               AND `mainevents_lookup`.`datestart` <= '2016-05-27 11:59:59' ) 
              OR ( `mainevents_lookup`.`dateend` >= '2016-02-27 00:00:00' 
                   AND `mainevents_lookup`.`dateend` <= '2016-05-27 11:59:59' ) 
              OR ( `mainevents_lookup`.`dateend` <= '2016-05-27 11:59:59' 
                   AND `mainevents_lookup`.`datestart` >= '2016-02-27 00:00:00' 
                 ) ) 
LIMIT  0, 30 

它正在尝试查找日期属于所选两个日期范围的商家信息。 DateStart是'2016-02-27 00:00:00',DateEnd是'2016-05-27 11:59:59'

出于某种原因,它一直给我带来与我想要找到的相反的结果。我知道答案就在我面前,任何人都可以帮我一把吗?

3 个答案:

答案 0 :(得分:1)

检查重叠日期范围 (StartA <= EndB) and (EndA >= StartB)

SELECT `mainevents`.`maineventid`   AS `MainEventID`, 
       `mainevents`.`maineventcode` AS `MainEventCode`, 
       `mainevents`.`datestart`     AS `DateStart`, 
       `mainevents`.`dateend`       AS `DateEnd`, 
       `mainevents`.`location`      AS `Location`, 
       `mainevents`.`name`          AS `Name` 
FROM   `mainevents`, 
       `mainevents_lookup` 
WHERE  `mainevents`.`maineventid` = `mainevents_lookup`.`maineventid` 
  AND `mainevents`.`categoryid` = 1 
  AND `mainevents_lookup`.`datestart` <= '2016-05-27 11:59:59'     
  AND `mainevents_lookup`.`dateend` >= '2016-02-27 00:00:00'
LIMIT  0, 30 

答案 1 :(得分:1)

不应该需要第二个OR条件,看起来最后的AND测试使用了错误的列(datestart而不是dateend)。

AND ( ( `mainevents_lookup`.`datestart` >= '2016-02-27 00:00:00' 
           AND `mainevents_lookup`.`datestart` <= '2016-05-27 11:59:59' ) 
          OR ( `mainevents_lookup`.`dateend` >= '2016-02-27 00:00:00' 
               AND `mainevents_lookup`.`dateend` <= '2016-05-27 11:59:59' ) 
) 

答案 2 :(得分:0)

我应该完成默认并验证初始数据。表中的数据不正确,查询正确地提取了未来事件,因为查找表中的日期范围在查询日期范围内。