截断错误的日期值:' 02:02:02 am'

时间:2016-09-24 08:05:16

标签: mysql sql datetime

当我插入这个时间' 02:02:02 am'使用以下查询到mysql时间字段:

$ ./bin/looppyrimid
1
2 3
4 5 6
7 8 9 10

显示以下错误

insert INTO invoices(name,phone,totalsum,givenmoney,date,time,moreinfo) VALUES ('f','2','2','2','1994-01-01',DATE_FORMAT('02:02:02 am','%h:%i:%s %p'),'AA')

如何解决?

不是我的时间字段的数据类型是Truncated incorrect date value: '02:02:02 am'

1 个答案:

答案 0 :(得分:1)

你很近但你应该使用str_to_time而不是

mysql> select str_to_date('02:02:02 am','%h:%i:%s %p');
+------------------------------------------+
| str_to_date('02:02:02 am','%h:%i:%s %p') |
+------------------------------------------+
| 02:02:02                                 |
+------------------------------------------+
1 row in set (0.00 sec)

我建议使用time数据类型来存储时间值H:i:s格式http://dev.mysql.com/doc/refman/5.7/en/time.html

,而不是时间戳。

更新: SO运行查询时出错 这是在mysql 5.5上运行的测试用例

mysql> create table invoices (
    ->    name varchar(30),
    ->    phone varchar(30),
    ->    totalsum varchar(30),
    ->    givenmoney varchar(30),
    ->    date date,
    ->    time time,
    ->    moreinfo varchar(30)
    -> );
Query OK, 0 rows affected (0.13 sec)

mysql> 
mysql> insert INTO invoices
    -> (name,phone,totalsum,givenmoney,date,time,moreinfo) 
    -> VALUES 
    -> ('f','2','2','2','1994-01-01',str_to_date('02:02:02 am','%h:%i:%s %p'),'AA');
Query OK, 1 row affected (0.04 sec)

mysql> select * from invoices ;
+------+-------+----------+------------+------------+----------+----------+
| name | phone | totalsum | givenmoney | date       | time     | moreinfo |
+------+-------+----------+------------+------------+----------+----------+
| f    | 2     | 2        | 2          | 1994-01-01 | 02:02:02 | AA       |
+------+-------+----------+------------+------------+----------+----------+
1 row in set (0.00 sec)

for 5.6这里是小提琴http://sqlfiddle.com/#!9/79e0c9/1