iT邦幫忙

3

以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 |
+----+------+

-- 整理table

optimize 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() 使用.
至於選用哪種,也沒有絕對,可以自行靈活搭配使用.


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言