2014-01-07 73 views
0

我不能繞過這一個我的頭......MySQL的選擇在不同的年份和月份的cols

創建表,並在其中一些轉儲數據

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 
當然這不正確的

...之後

任何指針?

謝謝。

+0

我認爲你可以做得比這更好一點。 – Strawberry

+0

http://dev.mysql.com/doc/refman/5.1/en/datetime.html – Mihai

回答

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

感謝Mihai,使用'CONCAT'將列組合成一個新的日期列,然後選擇語句正常工作。我正在使用舊的表/代碼,並不想重寫它的塊... – Sparki

0

這是一個提示,而不是一個答案 - 但我想利用其他格式化選項...

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