MySQL选择单独的年份和月份cols

时间:2014-01-07 17:38:50

标签: mysql sql

我无法理解这一个......

创建表并在其中转储一些数据

CREATE TABLE `_xxx` (
  `x` DECIMAL(10,5) NULL DEFAULT NULL,
  `x_year` INT(4) NULL DEFAULT NULL,
  `x_month` INT(2) NULL DEFAULT NULL);

insert into  _xxx (x, x_year, x_month) values (10,2010,1);
insert into  _xxx (x, x_year, x_month) values (20,2010,2);
insert into  _xxx (x, x_year, x_month) values (30,2010,3);
insert into  _xxx (x, x_year, x_month) values (40,2010,4);
insert into  _xxx (x, x_year, x_month) values (50,2010,5);
insert into  _xxx (x, x_year, x_month) values (60,2010,6);
insert into  _xxx (x, x_year, x_month) values (70,2010,7);
insert into  _xxx (x, x_year, x_month) values (80,2010,8);
insert into  _xxx (x, x_year, x_month) values (90,2010,9);
insert into  _xxx (x, x_year, x_month) values (11,2011,1);
insert into  _xxx (x, x_year, x_month) values (21,2011,2);
insert into  _xxx (x, x_year, x_month) values (31,2011,3);
insert into  _xxx (x, x_year, x_month) values (41,2011,4);
insert into  _xxx (x, x_year, x_month) values (51,2011,5);
insert into  _xxx (x, x_year, x_month) values (61,2011,6);
insert into  _xxx (x, x_year, x_month) values (71,2011,7);
insert into  _xxx (x, x_year, x_month) values (81,2011,8);
insert into  _xxx (x, x_year, x_month) values (91,2011,9);
insert into  _xxx (x, x_year, x_month) values (12,2012,1);
insert into  _xxx (x, x_year, x_month) values (22,2012,2);
insert into  _xxx (x, x_year, x_month) values (32,2012,3);
insert into  _xxx (x, x_year, x_month) values (42,2012,4);
insert into  _xxx (x, x_year, x_month) values (52,2012,5);
insert into  _xxx (x, x_year, x_month) values (62,2012,6);
insert into  _xxx (x, x_year, x_month) values (72,2012,7);
insert into  _xxx (x, x_year, x_month) values (82,2012,8);
insert into  _xxx (x, x_year, x_month) values (92,2012,9);

现在尝试在日期之前选择所有日期,在日期之后选择所有日期(两个日期之间的所有内容)......

SELECT * FROM _xxx WHERE x_year >= 2011 AND x_month >= 7

当然这不正确......

任何指针?

感谢。

2 个答案:

答案 0 :(得分:1)

它很尴尬,但它有效

SELECT *,DATE(CONCAT(x_year,'-',x_month,'-',01))dateColumn 
FROM _xxx 
HAVING dateColumn BETWEEN '2011-04-01' AND '2012-06-01'

Fiddle

您可以使用相同的公式创建DATE字段,以便对其进行索引。

答案 1 :(得分:0)

这是一个暗示,而不是答案 - 但我想利用其他格式化选项...

SELECT (2013,06) >= (2012,08) AND (2013,06) <= (2014,05) x;
+---+
| x |
+---+
| 1 |
+---+