MySql日期查询结果不正确

时间:2015-01-25 07:23:14

标签: mysql sql

当我运行以下查询时,它会返回Date_add (CURDATE() AND CURDATE(), interval 30 day)内日期的所有结果,但不包括Date_sub (CURDATE() AND CURDATE(), interval 15 day)的结果

我知道在使用deadline = '2015-01-15'

的精确子句进行查询时数据存在

可能出现什么问题?

SELECT bug_id, 
       bug_status, 
       resolution, 
       short_desc, 
       deadline 
FROM   bugs 
WHERE  bug_status IN ( 'RESOLVED' ) 
       AND deadline BETWEEN Curdate() AND Date_add(Curdate(), interval 30 day) 
        OR deadline BETWEEN Curdate() AND Date_sub(Curdate(), interval 15 day) 

2 个答案:

答案 0 :(得分:2)

订购between的兰特。所以,第二个between不正确。另外,您可能需要括号:

WHERE  bug_status IN ( 'RESOLVED' ) AND
       (deadline BETWEEN Curdate() AND Date_add(Curdate(), interval 30 day) OR
        deadline BETWEEN Date_sub(Curdate(), interval 15 day)  AND Curdate()
       )

我的意思是,您可能不想要括号,因此查询将是:

WHERE  (bug_status IN ( 'RESOLVED' ) AND
        deadline BETWEEN Curdate() AND Date_add(Curdate(), interval 30 day)
       ) OR
       deadline BETWEEN Date_sub(Curdate(), interval 15 day)  AND Curdate()

在这种情况下,括号是多余的,但它们澄清了逻辑。

答案 1 :(得分:1)

between的论点应始终为value BETWEEN low AND high。如果您翻转lowhigh,它将返回false。此外,您可以将两个条件统一为一个:

deadline BETWEEN Date_sub(Curdate(), interval 15 day) AND 
                 Date_add(Curdate(), interval 30 day)