在MySQL语句中包含日期的Where子句不起作用

时间:2015-04-20 09:51:26

标签: mysql date

表名: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-mm'格式的日期。

如何获得结果?

PS:在这种情况下,UNIX_TIMESTAMP()是否可以安全下注?

3 个答案:

答案 0 :(得分:3)

您永远不应将日期值存储为varchar并选择与datedatetimetimestamp

相关的mysql原生日期相关数据类型

但是在您的情况下,您需要在执行选择查询之前执行一些与日期相关的计算。请考虑下表

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        |
+------+----------------+

答案 1 :(得分:1)

使用STR_TO_DATE函数(字符串,格式);

http://www.mysqltutorial.org/mysql-str_to_date/

答案 2 :(得分:0)

您应该使用mysql日期时间functions或在mysql中使用int字段并存储UNIXTIMESTAMP并比较您已经在做的事情。我认为存储unixtimestamp是不合适的,因为你只需要一个月和一年而且你从unixtimestamp的优势中获益很多。