我有TIME
类型(00:00:00
)的列。我只想允许正值。因此,-05:30:00
例如,将是无效的。
有没有办法做到这一点?
我想为该列设置一个默认值,因此如果它收到“-05:00:00”值,它将将该值设置为“00:00:00”。
time_format( time, format )
如果需要,date_format( date, format )
您可以依赖MySQL
. 您还需要substring
和locate
函数来解析。
要将时间字段设置为默认或 +ve 部分时间数据,以下示例可以帮助您:
mysql> set @time_value='-23:51:48';
Query OK, 0 rows affected (0.00 sec)
示例 1:
mysql> insert
into time_table( time_field )
values ( if( locate( '-', @time_value ) = 1, '00:00:00', @time_value ) );
Query OK, 1 row affected (0.00 sec)
让我们看看插入了什么:
mysql> select time_field from time_table;
+------------+
| time_field |
+------------+
| 00:00:00 |
+------------+
1 row in set (0.00 sec)
示例 2:
mysql> insert
into time_table( time_field )
values ( substring( @time_value, ( locate( '-', @time_value ) + 1 ) ) );
Query OK, 1 row affected (0.00 sec)
示例 3:
mysql> insert
into time_table( time_field )
values
( substring( time_format( @time_value, '%H %k:%i:%s' ),
( locate( ' ', time_format( @time_value, '%H %k:%i:%s' ) ) + 1 )
)
);
Query OK, 1 row affected (0.00 sec)
在这:
H
: for Hour to return as 00
to23
k
: for Hour to return as 0
to23
i
:对于分钟,数字00
到59
s
: 秒返回00
至59
让我们看看插入了什么:
mysql> select time_field from time_table;
+------------+
| time_field |
+------------+
| 23:51:48 |
+------------+
1 row in set (0.00 sec)
有关格式说明符字符的更多详细信息,%k
请参阅date_format( date, format )