【问题标题】:MySQL decimal memory usage (signed v unsigned)MySQL 十进制内存使用情况(有符号与无符号)
【发布时间】:2015-12-26 02:47:25
【问题描述】:

我了解 MySQL 十进制数的内存存储要求(例如,DECIMAL(5,2) 需要 2 个字节用于 3 个整数,1 个用于小数。但我注意到十进制也可以是有符号或无符号的。

对于像 TINYINT 这样的数字,范围取决于它是有符号(-128 到 127)还是无符号(0-255)。那么我的问题是,如果小数是有符号或无符号的,它们的内存使用会改变吗? -999.99 到 999.99 会和 000.00 到 999.99 使用相同的内存吗?

【问题讨论】:

    标签: mysql decimal


    【解决方案1】:

    -999.99 到 999.99 会和 000.00 到 999.99 使用相同的内存吗?

    简短回答:是的。

    更长的答案:

    • 小数点左边的数字和右边的数字都被认为是整数。
    • 左侧有一个标志,但不占用任何额外空间。
    • 每组(左侧或右侧)9 位数字适合 4 个字节;少于 9 个占用 ceil(N/2) 个字节。

    一个简单的经验法则:“DECIMAL(m,n) 占用 m/2 字节。”它并不总是准确的,但非常接近。

    我认为 DECIMAL 的最后一次重大变化是在 5.0.5 中。

    【讨论】:

    • 如果我理解正确的话,decimal(13,2) 是 9 个字节,decimal(10,2) 是 5 个字节?
    • (13,2) 是 5+1 个字节:小数点左边 5 个字节,小数点右边再加 1 个字节。 (10,2) 是 4+1 字节。
    【解决方案2】:

    这将随着版本的变化而变化。以下是它在 5.6 中如何实现的信息。

    The MySQL docs不说标牌的效果,建议深入decimal2bin()的源码了解详情。里面有一个关于存储格式的大评论。

    This binary format is as follows:
      1. First the number is converted to have a requested precision and scale.
      2. Every full DIG_PER_DEC1 digits of intg part are stored in 4 bytes
         as is
      3. The first intg % DIG_PER_DEC1 digits are stored in the reduced
         number of bytes (enough bytes to store this number of digits -
         see dig2bytes)
      4. same for frac - full decimal_digit_t's are stored as is,
         the last frac % DIG_PER_DEC1 digits - in the reduced number of bytes.
      5. If the number is negative - every byte is inversed.
      5. The very first bit of the resulting byte array is inverted (because
         memcmp compares unsigned bytes, see property 2 above)
    

    关键是“5。如果数字是负数-每个字节都取反。”,所以答案是有符号或无符号对DECIMAL存储大小没有影响。

    【讨论】:

    • 谢谢。所以似乎使小数无符号的唯一原因是防止无效条目。
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 2020-07-04
    • 2016-05-07
    • 2018-08-04
    • 2013-04-15
    • 2012-10-25
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多