布尔混淆或微积分混淆

我正在为一个网站设计一个数据库,在那里我需要使用一个布尔数据类型来存储只有2个状态,真或假。我正在使用 MySQL。
在使用 phpMyAdmin 设计数据库时,我发现我同时具有 BOOLEAN 数据类型和 TINYINT 数据类型。
我看过不同的文章,有的说 TINYINT 和 BOOLEAN 是一样的,没有区别。有人说在 MySQL 中 BOOLEAN 被转换成了 TINYINT。

我的问题是,如果它们都是相同的,为什么会有两个? 应该只有一个。

以下是我读到的文章的参考文献:
Http://www.careerride.com/mysql-bool-tinyint-bit.aspx
Http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html

202132 次浏览

MySQL does not have internal boolean data type. It uses the smallest integer data type - TINYINT.

The BOOLEAN and BOOL are equivalents of TINYINT(1), because they are synonyms.

Try to create this table -

CREATE TABLE table1 (
column1 BOOLEAN DEFAULT NULL
);

Then run SHOW CREATE TABLE, you will get this output -

CREATE TABLE `table1` (
`column1` tinyint(1) DEFAULT NULL
)

The Newest MySQL Versions have the new BIT data type in which you can specify the number of bits in the field, for example BIT(1) to use as Boolean type, because it can be only 0 or 1.

As of MySql 5.1 version reference

BIT(M) =  approximately (M+7)/8 bytes,
BIT(1) =  (1+7)/8 = 1 bytes (8 bits)

=========================================================================

TINYINT(1) take 8 bits.

https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html