将列从varchar更改为时间戳,保留值

时间:2014-04-08 16:14:36

标签: mysql

我有一个列(varchar),它以24h格式保存像“hh:mm”这样的值。 STR_TO_DATE(column, '%H:%i')正确解析。

如何更改表格 - 将值更改为TIMESTAMP - 并保留值?

1 个答案:

答案 0 :(得分:1)

如果'%H:%i'的格式已正确维护,那么您可以alter列定义如下:

alter table table_name modify column column_name time;

演示

mysql> create table so.tm( t varchar(10) );
mysql> desc tm;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| t     | varchar(10) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

mysql> insert into tm values ( '09:45' ), ( '18:24' ), ( 'ravin' );
Query OK, 3 rows affected (0.08 sec)

mysql> select t, str_to_date( t, '%H:%i' ) from tm;
+-------+---------------------------+
| t     | str_to_date( t, '%H:%i' ) |
+-------+---------------------------+
| 09:45 | 09:45:00                  |
| 18:24 | 18:24:00                  |
| ravin | NULL                      |
+-------+---------------------------+

如果字段中包含的数据没有可解析的时间数据,请说“ravin''”,alter命令会抛出以下错误。

mysql> alter table tm modify column t time;
ERROR 1292 (22007): Incorrect time value: 'ravin' for column 't' at row 3

mysql> select t, str_to_date( t, '%H:%i' ) from tm;
+-------+---------------------------+
| t     | str_to_date( t, '%H:%i' ) |
+-------+---------------------------+
| 09:45 | 09:45:00                  |
| 18:24 | 18:24:00                  |
| ravin | NULL                      |
+-------+---------------------------+
3 rows in set, 1 warning (0.00 sec)

mysql> delete from tm where t is null;
Query OK, 0 rows affected (0.06 sec)

mysql> alter table tm modify column t time;
Query OK, 2 rows affected (1.05 sec)

mysql> desc tm; select t from tm;
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| t     | time | YES  |     | NULL    |       |
+-------+------+------+-----+---------+-------+

+----------+
| t        |
+----------+
| 09:45:00 |
| 18:24:00 |
+----------+