表名:DemoTable。
外地共计:2
字段:
id (int, auto increment, primary key)
month_and_year (varchar(10))month_and_year包含日期为“2015-03”、“2015-01”、“2014-12”等.
我试图从“2014-10”到“2015-03”之间的表格中获得价值。
SELECT * FROM DemoTable where month_and_year>='2014-10' AND month_and_year<='2015-03' ORDER BY month_and_year DESC 查询不提供所需的输出,因为month_and_year字段具有varchar数据类型。更改varchar到日期数据类型是不可能的,因为日期数据类型不接受‘yyyy’格式的日期。
如何取得结果呢?
PS:在这种情况下,UNIX_TIMESTAMP()是一个安全的赌注吗?
发布于 2015-04-20 10:34:41
您不应该将日期值存储为varchar,并选择mysql本机日期相关数据类型,如date、datetime或timestamp。
但是,在您的示例中,您需要在执行select查询之前进行一些与日期相关的计算。考虑下表
mysql> select * from test ;
+------+----------------+
| id | month_and_year |
+------+----------------+
| 1 | 2014-10 |
| 2 | 2014-10 |
| 3 | 2014-09 |
| 4 | 2014-11 |
| 5 | 2015-01 |
| 6 | 2014-08 |
+------+----------------+现在的方法是
首先将varchar转换为实际日期。
然后对于下限,总是从一年的第一天开始比较月份的值。
上限将持续到月底。
因此,查询变成
select * from test
where
date_format(
str_to_date(
month_and_year,'%Y-%m'
),'%Y-%m-01'
)
>=
date_format(
str_to_date('2014-10','%Y-%m'
),'%Y-%m-01'
)
and
last_day(
date_format(
str_to_date(month_and_year,'%Y-%m'
),'%Y-%m-01'
)
)
<=
last_day(
date_format(
str_to_date('2015-03','%Y-%m'
),'%Y-%m-01'
)
);输出将与
+------+----------------+
| id | month_and_year |
+------+----------------+
| 1 | 2014-10 |
| 2 | 2014-10 |
| 4 | 2014-11 |
| 5 | 2015-01 |
+------+----------------+发布于 2015-04-20 10:35:35
使用函数STR_TO_DATE(string,format);
日期/日期
发布于 2015-04-20 09:55:46
您应该在mysql中使用mysql、date time 函数或int字段,并存储UNIXTIMESTAMP并进行比较,就像您已经在做的那样。我认为存储unixtimestamp太过分了,因为您只需要一个月和一年,而且您不会从unixtimestamp优势中获益很多。
https://stackoverflow.com/questions/29744521
复制相似问题