0

我有TIME类型(00:00:00)的列。我只想允许正值。因此,-05:30:00例如,将是无效的。

有没有办法做到这一点?

4

1 回答 1

0

我想为该列设置一个默认值,因此如果它收到“-05:00:00”值,它将将该值设置为“00:00:00”。

time_format( time, format )如果需要,date_format( date, format )您可以依赖MySQL. 您还需要substringlocate函数来解析。

要将时间字段设置为默认或 +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)  

在这:

  1. H: for Hour to return as 00to23
  2. k: for Hour to return as 0to23
  3. i:对于分钟,数字0059
  4. s: 秒返回0059

让我们看看插入了什么:

mysql> select time_field from time_table;
+------------+
| time_field |
+------------+
| 23:51:48   |
+------------+
1 row in set (0.00 sec)

有关格式说明符字符的更多详细信息,%k请参阅date_format( date, format )

于 2012-06-05T15:19:18.037 回答