mysql - 选择开始年份和开始月份到结束年份和结束月份之间的行?

时间:2012-08-29 06:28:40

标签: mysql sql database

我正在尝试选择给定年份和月份范围的行。 (即:从<start year>+<start month><end year>+<end month>) 我尝试了下面的查询,但我得到了意想不到的行。我错过了什么吗?

SELECT * FROM table AS t
WHERE 
((YEAR(t.column1)='<start year>' AND MONTH(t.column1)>='<start month>') OR
(YEAR(t.column1)>'<start year>' AND YEAR(t.column1)<'<end year>') OR
(YEAR(t.column1)='<end year>' AND MONTH(t.column1)<='<end month>'))

3 个答案:

答案 0 :(得分:5)

如果开始年份和结束年份不同,您的查询只能正常工作。如果它们相同,则查询将返回该年份的所有行。你需要分开处理这个案子:

(
    start_year != end_year and 
    (
        (YEAR(t.column1)='<start year>' AND MONTH(t.column1)>='<start month>') OR  
        (YEAR(t.column1)>'<start year>' AND YEAR(t.column1)<'<end year>') OR  
        (YEAR(t.column1)='<end year>' AND MONTH(t.column1)<='<end month>')
    )
)
OR (start_year = end_year and MONTH(t.column1) >= start_month
                          and MONTH(t.column1) <= end_month)

然而,这可以大大简化:

YEAR(t.column1) * 12 + MONTH(t.column1) >= start_year * 12 + start_month
and YEAR(t.column1) * 12 + MONTH(t.column1) <= end_year * 12 + end_month

或更短的between

YEAR(t.column1) * 12 + MONTH(t.column1)
BETWEEN start_year * 12 + start_month and end_year * 12 + end_month

答案 1 :(得分:1)

试试这个:

... WHERE t.column1>="startYear-startMonth-01" AND t.column1<="endYear-endMonth-31"

答案 2 :(得分:1)

您可以尝试这样的事情:

SELECT * FROM table AS t
WHERE  t.column1
       BETWEEN STR_TO_DATE(CONCAT('<start year>', '<start month>', '01'), '%Y%m%d') AND 
               LAST_DAY(STR_TO_DATE(CONCAT('<start end>', '<start end>','01'), '%Y%m%d'));

这应该会更好,因为它将使用列column1中的索引。