简体   繁体   English

如何在MySQL中的DATETIME中从毫秒中删除尾随零

[英]How to remove Trailing Zero from milliseconds in DATETIME in MySQL

How can I remove trailing zeros occurring in higher precision of DATETIME in MySQL. 如何在MySQL中以较高的DATETIME精度消除尾随零。

Sample input/output: 样本输入/输出:

2018-04-13 13:02:32.948000     =>    2018-04-13 13:02:32.948

Based on the MySQL-Doc there should be a "fsp" parameter for DATETIME-fields. 基于MySQL-Doc,DATETIME字段应该有一个“ fsp”参数。

CREATE TABLE fractest( c1 TIME(2), c2 DATETIME(2), c3 TIMESTAMP(2) );

mysql> INSERT INTO fractest VALUES ('17:51:04.777', '2014-09-08 17:51:04.777', '2014-09-08 17:51:04.777');

mysql> SELECT * FROM fractest;
+-------------+------------------------+------------------------+
| c1          | c2                     | c3                     |
+-------------+------------------------+------------------------+
| 17:51:04.78 | 2014-09-08 17:51:04.78 | 2014-09-08 17:51:04.78 |
+-------------+------------------------+------------------------+

But it's not possible to remove trailing zeros dynamically you have to fix the length of the fractional seconds precision. 但是不可能动态删除尾随零,而必须固定小数秒精度的长度。

Source: Fractional Seconds in Time Values 来源: 时间值的小数秒

If you output the DATETIME value with milliseconds directly MySQL removes the trailing zeros. 如果直接以毫秒为单位输出DATETIME值,则MySQL会删除尾随的零。

CREATE TABLE test (
    colDateTime DATETIME(6)
);

INSERT INTO test VALUES ('2018-04-17 11:12:13.444000');

Now we use the following SELECT statement: 现在,我们使用以下SELECT语句:

SELECT * FROM test; -- output: 2018-04-17T11:12:13.444Z (0 at the end are removed by MySQL).

The only way you get the zeros at the end is using the DATE_FORMAT : 最后获得零的唯一方法是使用DATE_FORMAT

SELECT DATE_FORMAT(colDateTime, '%f') FROM test; -- output: 444000

In this case you can TRIM the zero of this string value: 在这种情况下,您可以将该字符串值的零TRIM

SELECT TRIM(TRAILING '0' FROM DATE_FORMAT(colDateTime, '%Y-%m-%d %H:%i:%s.%f')) FROM test;

demo: http://sqlfiddle.com/#!9/b0655f/5/2 演示: http : //sqlfiddle.com/#!9/b0655f/5/2

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

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