简体   繁体   English

如何仅将正值设置为默认值

[英]How to set the default value for only positive time

I have column with TIME type( 00:00:00 ). 我有TIME类型的列( 00:00:00 )。 I want to allow only positive values. 我只允许使用正值。 So, -05:30:00 , for example, would be invalid. 因此,例如-05:30:00无效。

Is there a way of doing it? 有办法吗?

I want to set a DEFAULT VALUE for the column, so if it recieve '-05:00:00' value it will set the value to '00:00:00'. 我想为该列设置一个默认值,因此,如果它接收到“ -05:00:00”的值,它将把该值设置为“ 00:00:00”。

You can depend on time_format( time, format ) and if required on date_format( date, format ) functions in MySQL . 您可以依赖于time_format( time, format ) ,如果需要time_format( time, format )还可以依赖MySQL date_format( date, format )函数。 You also require substring and locate functions to parse. 您还需要substringlocate要解析的函数。

To set a time field to with default or +ve part of time data, following examples helps you: 要将时间字段设置为默认或部分时间数据,以下示例将帮助您:

mysql> set @time_value='-23:51:48';
Query OK, 0 rows affected (0.00 sec)

Example 1 : 范例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)  

Let us see what is inserted: 让我们看看插入了什么:

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

Example 2 : 范例2

mysql> insert
         into time_table( time_field )
         values ( substring( @time_value, ( locate( '-', @time_value ) + 1 ) ) );
Query OK, 1 row affected (0.00 sec)  

Example 3 : 例子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)  

In this: 在此:

  1. H : for Hour to return as 00 to 23 H :小时返回0023
  2. k : for Hour to return as 0 to 23 k :小时返回023
  3. i : for Minutes, numeric 00 to 59 i :分钟,数字0059
  4. s : for Seconds to return as 00 to 59 s :秒以0059返回

Let us see what is inserted: 让我们看看插入了什么:

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

For more details on format specifier characters like %k refer to date_format( date, format ) 有关%k类的格式说明符的更多详细信息,请参考date_format( date, format )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM