MySQL将字节转换为千字节,兆字节,千兆字节 [英] MySQL Convert Bytes to Kilobytes, Megabytes, Gigabytes

查看:473
本文介绍了MySQL将字节转换为千字节,兆字节,千兆字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志表,以字节为单位存储各种文件大小.我希望能够查询数据库并返回已转换为MB GB等的最小可能的浮点数.目前,我可以返回MB的值,但是如何继续进一步除以最小值并追加单位呢? /p>

I have a logs table that stores various file sizes in bytes. I want to be able to query the database and return the smallest possible float which has been converted to MB GB etc. At present I can return the value in MB but how do I continue to divide further to smallest value and append the unit?

SELECT CONCAT( ROUND( SUM( data_transferred ) /1048576, 2 ) ,  ' MB' ) 
FROM  `logs`

任何帮助将不胜感激.

更新:

基于提供的链接voodoo417,我将查询更新为以下内容,该查询将输出最相关的文件大小到小数点后两位,并附加单位(1000字节,1 KB,500 MB,2 GB等):

Based on the link voodoo417 provided I updated my query to the following, which will output the most relevant file size to two decimal places and append the unit (1000 Bytes, 1 KB, 500 MB, 2 GB, etc):

SET @bytes := (SELECT SUM(data_transferred) FROM wp_ddownload_statistics);

SELECT
    CASE
WHEN ABS(@bytes) < 1024 THEN CONCAT( ROUND( @bytes, 2 ), ' Bytes')
      WHEN ABS(@bytes) < 1048576 THEN CONCAT( ROUND( (@bytes/1024), 2 ), ' KB')
      WHEN ABS(@bytes) < 1073741824 THEN CONCAT( ROUND( (@bytes/1048576), 2 ), ' MB')
      WHEN ABS(@bytes) < 1099511627776 THEN CONCAT( ROUND( (@bytes/1073741824), 2 ), ' GB' )
      WHEN ABS(@bytes) < 1125899906842624 THEN CONCAT( ROUND( (@bytes/1099511627776), 2 ), ' TB')
      WHEN ABS(@bytes) < 1152921504606846976 THEN CONCAT( ROUND( (@bytes/1125899906842624), 2 ), ' PB' )
      WHEN ABS(@bytes) < 1180591620717411303424 THEN CONCAT( ROUND( (@bytes/1152921504606846976) ,2), ' EB' )
      WHEN ABS(@bytes) < 1208925819614629174706176 THEN CONCAT( ROUND( (@bytes/1180591620717411303424), 2), ' ZB' )
      WHEN ABS(@bytes) < 1237940039285380274899124224 THEN CONCAT( ROUND( (@bytes/1208925819614629174706176), 2), ' YB' )
      WHEN ABS(@bytes) < 1267650600228229401496703205376 THEN CONCAT( ROUND( (@bytes/1237940039285380274899124224), 2), ' BB' )
    END

推荐答案

我知道这是一个老问题,但是最近我在寻找相同的东西,发现MySQL 5.7添加了

I know this is an old question, but I was looking for the same thing recently, and found out that MySQL 5.7 added format_bytes function exactly for this purpose:

mysql> SELECT format_bytes(512), format_bytes(18446644073709551615);
+-------------------+------------------------------------+
| format_bytes(512) | format_bytes(18446644073709551615) |
+-------------------+------------------------------------+
| 512 bytes         | 16383.91 PiB                       |
+-------------------+------------------------------------+

这篇关于MySQL将字节转换为千字节,兆字节,千兆字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆