[英]MYSQL: DATE function returning null in Select query
我有一個所有列類型都為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
誰能告訴我查詢中出了什么問題?
結構圖
應該是%Y
而不是%y.
%Y
需要4位數字的年份。
DATEDIFF(NOW(),STR_TO_DATE(column_14,"%Y-%m-%d")
))
如果您選擇了錯誤的格式或函數檢測到超出范圍的月份或日期,則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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.