我的所有列类型的数据都为text
,甚至日期也存储在文本类型列中。现在,当我使用select
查询来访问列的工作查找时,但是当我尝试对该列执行任何日期操作时,它总是返回null。
表:
如果我正在运行查询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
任何人都可以告诉我我的查询有什么问题吗?
结构视图
答案 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)