2

我正在尝试为给定的年份和月份范围选择行。(即:从<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>'))
4

3 回答 3

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
于 2012-08-29T06:36:17.860 回答
1

试试这个:

... WHERE t.column1>="startYear-startMonth-01" AND t.column1<="endYear-endMonth-31"
于 2012-08-29T06:32:38.907 回答
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'));

这应该会表现得更好,因为它将使用 column 中的索引column1

于 2012-08-29T06:34:40.493 回答