在 MySQL 中,BIT 列是否适合存储 5、6 或 7 字节整数?

发布于 2024-09-14 04:57:22 字数 464 浏览 0 评论 0原文

我有一个表,我想保留其大小,并且其中一列可以被视为 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 integers
  • SMALLINT, for 2-byte integers
  • MEDIUMINT, for 3-byte integers
  • INT, for 4-byte integers
  • BIGINT, 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

套路撩心 2024-09-21 04:57:22

使用本机整数类型,例如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.

冰火雁神 2024-09-21 04:57:22

MySQL 将 BIT 视为文本数据而不是数字。通常这就是应该避免使用 BIT 的原因 - 它可能有点令人困惑。例如,我们想将数字 57 存储在 BIT(8) 列中。数字 57 将被存储为“b”00111001,即 57 的二进制表示。但它会显示为 9,因为 57 是“9”的 ASCII 码。要获得正确的整数值,您必须将列数据转换为数值。您可以使用以下方法测试此行为:

CREATE TABLE testbit(a BIT(8));
INSERT INTO testbit VALUES (b'00111001');
INSERT INTO testbit VALUES (57);
SELECT a FROM testbit;
SELECT a+0 FROM testbit;

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:

CREATE TABLE testbit(a BIT(8));
INSERT INTO testbit VALUES (b'00111001');
INSERT INTO testbit VALUES (57);
SELECT a FROM testbit;
SELECT a+0 FROM testbit;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文