我正在尝试为给定的年份和月份范围选择行。 (即:从 <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>'))
最佳答案
只有开始年份和结束年份不同时,您的查询才能正常工作。如果它们相同,则查询返回当年的所有行。您需要单独处理这种情况:
(
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
关于mysql - 选择开始年份和开始月份到结束年份和结束月份之间的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12172035/