从time\u format()中删除00个值

hzbexzde  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(389)

从此查询

SELECT TIME_FORMAT("19:00:00", "%H Hours, %i Minutes, %s Seconds");

我知道结果了 19 Hours, 00 Minutes, 00 Seconds 我想要的是 19 Hours 只有 Minutes and Seconds = 00 .
如果我有 19:00:55 我希望得到 19 Hours, 55 Seconds 如果我有 19:55:00 我希望得到 19 Hours, 55 Minutes 通过移除 00 使用sql的值

smdncfj3

smdncfj31#

我测试了这个:

SET @t = '19:00:00';

SELECT CONCAT_WS(', ', 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%H'), '00'), ' hours'), 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%i'), '00'), ' minutes'), 
  CONCAT(NULLIF(TIME_FORMAT(@t, '%s'), '00'), ' seconds')) AS time_expr;

输出:

+-----------+
| time_expr |
+-----------+
| 19 hours  |
+-----------+

当我安排时间做别的事情时:

SET @t = '19:00:05';

输出:

+----------------------+
| time_expr            |
+----------------------+
| 19 hours, 05 seconds |
+----------------------+

它甚至可以处理零小时:

SET @t = '00:43:00';

输出:

+------------+
| time_expr  |
+------------+
| 43 minutes |
+------------+
axzmvihb

axzmvihb2#

这是比尔答案的一个微小变化,它处理时间部分的复数:

SELECT CONCAT_WS(', ', 
                 CONCAT(hour(t), ' hour', (case hour(t) when 0 then NULL when 1 then '' else 's' end)), 
                 CONCAT(minute(t), ' minute', (case minute(t) when 0 then NULL when 1 then '' else 's' end)), 
                 CONCAT(second(t), ' second', (case second(t) when 0 then NULL when 1 then '' else 's' end))
                ) AS time_expr
from (SELECT CAST('19:01:01' as time) as t) x
li9yvcax

li9yvcax3#

你可以试试这个。

SELECT TIME_FORMAT( "19:00:00", 
    CONCAT(IF(HOUR("19:00:00") <> 0, "%H Hours", "") ,
    IF(MINUTE("19:00:00") <> 0, ", %i Minutes", "") ,
    IF(SECOND("19:00:00") <> 0, ", %s Seconds", ""))
);

相关问题