如何根据输入数据显示未来30天的记录?

时间:2015-11-05 11:15:45

标签: mysql

来自用户界面, 用户可以选择日期并单击提交按钮, 根据输入字段如何显示未来30天的记录?

这是我的sqlfiddle http://sqlfiddle.com/#!9/b1f3b/1

目前我正在使用如下所示的

select * from historical_data
where current_day between '01-OCT-2015' and '07-OCT-2015'

请您告诉我如何为此撰写查询?

1 个答案:

答案 0 :(得分:1)

使用正确的数据类型。使用datedecimal之类的内容。这些不是varchar

您的代码:

create table historical_data
(
current_day varchar(50) ,
open_value varchar(10)
);

INSERT INTO historical_data (current_day,open_value) values ('01-OCT-2015','23.50');
INSERT INTO historical_data (current_day,open_value) values ('03-OCT-2015','26.50');
INSERT INTO historical_data (current_day,open_value) values ('05-OCT-2015','21.50');
INSERT INTO historical_data (current_day,open_value) values ('03-Strawberries','33.44');


select * from historical_data
where current_day between '01-OCT-2015' and '07-OCT-2015'

哎呀,你有草莓

相反,请执行:

create table historical_data2
(   id int auto_increment primary key,
    current_day date not null ,
    open_value decimal(10,2) not null
);
truncate table historical_data2;
INSERT INTO historical_data2 (current_day,open_value) values ('2015-09-01','11.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-10-01','23.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-10-03','26.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-10-04','21.50');
INSERT INTO historical_data2 (current_day,open_value) values ('03-Strawberries','33.44'); -- Error 1292: Incorrect date value
INSERT INTO historical_data2 (current_day,open_value) values ('2015-10-31','22.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-11-01','33321.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-11-02','4443321.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-11-03','55533321.50');
INSERT INTO historical_data2 (current_day,open_value) values ('2015-11-04','66633321.50');

利用内置mysql的Date and Time Functions功能,如add_addinterval功能。当您使用适当的数据类型时,这些可用。加上数学运算正确,它们占用的空间更少。

select * from historical_data2 
where current_day between '2015-10-02' and DATE_ADD(date('2015-10-02'), INTERVAL 1 MONTH)
+----+-------------+------------+
| id | current_day | open_value |
+----+-------------+------------+
|  3 | 2015-10-03  |      26.50 |
|  4 | 2015-10-04  |      21.50 |
|  5 | 2015-10-31  |      22.50 |
|  6 | 2015-11-01  |   33321.50 |
|  7 | 2015-11-02  | 4443321.50 |
+----+-------------+------------+

外卖:使用正确的数据类型