在 MySQL 中,BIT 列是否适合存储 5、6 或 7 字节整数?
我有一个表,我想保留其大小,并且其中一列可以被视为 5 字节无符号整数。这是我不需要进行搜索的列。
MySQL 提供整数数据类型
TINYINT
,对于 1 字节整数SMALLINT
,对于 2 字节整数MEDIUMINT
,对于 3 字节整数INT
,对于 4 字节整数BIGINT
,对于 8 字节整数。
但它还提供 BIT(M)
,即 1 ≤ M ≤ 64。它(有效)存储从 0 到 2M-1 的无符号整数。是否有理由避免使用 BIT(40)
列来存储 5 字节整数? (正如我所说,我不需要按此列进行搜索。因此,与查询执行速度相关的任何困难都可以忽略。)
I have a table whose size I'd like to keep down, and one of the columns can be treated as a 5-byte unsigned integer. This is a column that I won't need to search by.
MySQL offers integer datatypes
TINYINT
, for 1-byte integersSMALLINT
, for 2-byte integersMEDIUMINT
, for 3-byte integersINT
, for 4-byte integersBIGINT
, for 8-byte integers.
But it also offers BIT(M)
, for 1 ≤ M ≤ 64. This stores (effectively) an unsigned integer from 0 to 2M-1. Is there a reason to avoid using a BIT(40)
column to store a 5-byte integer? (As I said, I will not need to search by this column. Any difficulties relating to query execution speed may therefore be ignored.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用本机整数类型,例如tinyint。
使用位字段不会节省任何字节。也就是说,1 到 8 位的位字段占用 1 个字节,因此占用的空间与tinyint 一样多。
此外,如果您只想将位域用作数字,则使用位域会有点困难。
编辑:实际上,在某些情况下它可能会节省一些字节。但是,我仍然建议使用整数类型。
Use the native integer types, such as tinyint.
Using a bit field does not save any bytes. That is, a bit field of 1 to 8 bits takes 1 byte and will thus occupy as much space as a tinyint.
Also, bitfields are a bit harder to work with if you only want to use them as numbers.
Edit: Actually, in some cases it may save some bytes. However, I would still advice using the integer types.
MySQL 将 BIT 视为文本数据而不是数字。通常这就是应该避免使用 BIT 的原因 - 它可能有点令人困惑。例如,我们想将数字 57 存储在 BIT(8) 列中。数字 57 将被存储为“b”00111001,即 57 的二进制表示。但它会显示为 9,因为 57 是“9”的 ASCII 码。要获得正确的整数值,您必须将列数据转换为数值。您可以使用以下方法测试此行为:
MySQL treats BIT as textual data and not numbers. Usually this is the reason working with BIT should be avoided - it may be a little bit confusing. For example, we want to store number 57 in BIT(8) column. The number 57 will be stored as `b'00111001' i.e. binary representative of 57. But it will be displayed as 9 as 57 is ASCII code of '9'. To get proper integer value you have convert columns data to numerical value. You can test this behaviour with: