以Postgresql为主,再聊聊资料库 MySQL bit boolean tinyint 的空间使用探讨

create table usebool (  id int unsigned auto_increment primary key, tf bool default false);create table usebit (  id int unsigned auto_increment primary key, tf bit(1) default b'0');create table usetiny (  id int unsigned auto_increment primary key, tf tinyint unsigned default 0);insert into usebool(tf)select 0  from information_schema.KEYWORDS;insert into usebit(tf)select b'0'  from information_schema.KEYWORDS;insert into usetiny(tf)select 0  from information_schema.KEYWORDS;-- 查看内容select * from usebool limit 1;+----+------+| id | tf   |+----+------+|  1 |    0 |+----+------+select *, bin(tf) from usebit limit 1;+----+------------+---------+| id | tf         | bin(tf) |+----+------------+---------+|  1 | 0x00       | 0       |+----+------------+---------+select * from usetiny limit 1;+----+------+| id | tf   |+----+------+|  1 |    0 |+----+------+-- 整理tableoptimize table usebool;optimize table usebit;optimize table usetiny;-- 查看使用空间select TABLE_NAME     , DATA_LENGTH  from information_schema.tables  where TABLE_SCHEMA = 'miku'   and TABLE_NAME like 'use%';+------------+-------------+| TABLE_NAME | DATA_LENGTH |+------------+-------------+| usebit     |       49152 || usebool    |       49152 || usetiny    |       49152 |+------------+-------------+-- 三个 table size 相同

由上面的操作,可以观察到,三种方式使用的空间相同.bool 其实内部使用了 tinyint unsigned.
但是使用bool,有利于符合 ANSI SQL,日后要将DDL 在其他资料库使用时,较为方便.
使用tinyint unsigned 可以明确看出使用的格式,但是会有不小心输入了 大于 1 的情况,
判断时需要使用 = 0 , != 0, <> 0 .
使用 bit(1), 还要搭配 bin() 使用.
至于选用哪种,也没有绝对,可以自行灵活搭配使用.


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章