MYSQL:DATE函数在Select query

时间:2017-04-25 12:20:43

标签: mysql

我的所有列类型的数据都为text,甚至日期也存储在文本类型列中。现在,当我使用select查询来访问列的工作查找时,但是当我尝试对该列执行任何日期操作时,它总是返回null。

表:

enter image description here

如果我正在运行查询select column_14 from mytable where id = 2它的工作正常但是当我试图找到今天日期和column_14之间的差异时,它总是返回null

查询正在运行:

select DATEDIFF(NOW(),STR_TO_DATE(column_14,"%y-%m-%d")) from `mytable` where id = 2

enter image description here

任何人都可以告诉我我的查询有什么问题吗?

结构视图

enter image description here

2 个答案:

答案 0 :(得分:2)

应该是%Y而不是%y. %Y需要4位数。

DATEDIFF(NOW(),STR_TO_DATE(column_14,"%Y-%m-%d")

答案 1 :(得分:1)

如果您选择了错误的格式,或者函数检测到超出范围的月份或日期编号,则

Str_to_date将返回空值。在您的示例中,您选择了错误的格式%y应该是%Y。以下是可能发生的一些样本。 (nb:str_to_date很差,并且没有检查一个月有效的天数)

MariaDB [sandbox]> create table t (dt text);
Query OK, 0 rows affected (0.28 sec)

MariaDB [sandbox]> insert into t values ('2017-13-01'),('2017-04-31'),('2017-04-33'),('2017-04-03'),('birth_date');
Query OK, 5 rows affected (0.02 sec)
Records: 5  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select str_to_date(dt,'%y-%m-%d') Invalid_year_format,
    -> str_to_date(dt,'%Y-%m-%d') Valid_year_format_MM_and_DD,
    -> datediff(now(),str_to_date(dt,'%Y-%m-%d')) datediff_examples
    -> from t;
+---------------------+-----------------------------+-------------------+
| Invalid_year_format | Valid_year_format_MM_and_DD | datediff_examples |
+---------------------+-----------------------------+-------------------+
| NULL                | NULL                        |              NULL |
| NULL                | 2017-04-31                  |                -6 |
| NULL                | NULL                        |              NULL |
| NULL                | 2017-04-03                  |                22 |
| NULL                | NULL                        |              NULL |
+---------------------+-----------------------------+-------------------+
5 rows in set, 11 warnings (0.00 sec)