114

在什么情况下你会使用哪个?有很大的不同吗?持久性引擎通常使用哪个来存储布尔值?

4

6 回答 6

133

TINYINT 是一个 8 位整数值,一个 BIT 字段可以存储 1 位 BIT(1) 和 64 位 BIT(64)。对于布尔值,BIT(1) 很常见。

于 2008-11-14T14:39:01.250 回答
62

来自数字类型概述

位[(M)]

位域类型。M 表示每个值的位数,从 1 到 64。如果省略 M,则默认为 1。

这种数据类型在 MySQL 5.0.3 中为 MyISAM 添加,并在 5.0.5 中扩展到 MEMORY、InnoDB、BDB 和 NDBCLUSTER。在 5.0.3 之前,BIT 是 TINYINT(1) 的同义词。

TINYINT[(M)] [未签名] [ZEROFILL]

一个非常小的整数。有符号范围是 -128 到 127。无符号范围是 0 到 255。

Additionally consider this;

BOOL, BOOLEAN

These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.

于 2008-11-14T14:40:31.560 回答
43

All these theoretical discussions are great, but in reality, at least if you're using MySQL and really for SQLServer as well, it's best to stick with non-binary data for your booleans for the simple reason that it's easier to work with when you're outputting the data, querying and so on. It is especially important if you're trying to achieve interoperability between MySQL and SQLServer (i.e. you sync data between the two), because the handling of BIT datatype is different in the two of them. SO in practice you will have a lot less hassles if you stick with a numeric datatype. I would recommend for MySQL to stick with BOOL or BOOLEAN which gets stored as TINYINT(1). Even the way MySQL Workbench and MySQL Administrator display the BIT datatype isn't nice (it's a little symbol for binary data). So be practical and save yourself the hassles (and unfortunately I'm speaking from experience).

于 2011-02-08T12:34:06.793 回答
12

BIT 应该只允许 0 和 1(如果字段未定义为 NOT NULL,则为 NULL)。TINYINT(1) 允许任何可以存储在单个字节中的值,-128..127 或 0..255,具体取决于它是否是无符号的(1 表示您打算只使用单个数字,但它确实不会阻止您存储更大的值)。

对于早于 5.0.3 的版本,BIT 被解释为 TINYINT(1),因此没有区别。

BIT 具有“这是一个布尔值”语义,并且某些应用程序会以相同的方式考虑 TINYINT(1)(由于 MySQL 过去处理它的方式),因此如果应用程序检查类型,则可能会将列格式化为复选框并据此决定格式。

于 2008-11-14T14:39:25.603 回答
6

可能是错的,但是:

Tinyint 是 0 到 255 之间的整数

位是 1 或 0

因此对我来说 bit 是布尔值的选择

于 2008-11-14T14:36:13.970 回答
2

From my experience I'm telling you that BIT has problems on linux OS types(Ubuntu for ex). I developped my db on windows and after I deployed everything on linux, I had problems with queries that inserted or selected from tables that had BIT DATA TYPE.

Bit is not safe for now. I changed to tinyint(1) and worked perfectly. I mean that you only need a value to diferentiate if it's 1 or 0 and tinyint(1) it's ok for that

于 2014-05-05T09:54:14.680 回答