导读
你真的知道CHAR和VARCHAR类型在存储和读取时的区别吗?
还是先抛几条结论吧:
1、存储的时候,CHAR总是会补足空格后再存储,不管用户插入数据时尾部有没有包含空格。
2、存储的时候,VARCHAR不会先补足空格后再存储,但如果是用户在插入时特地加了空格那就会如实存储,而不会给删除。
3、读取数据时,CHAR总是会删除尾部空格(哪怕是写入时包含空格)。
4、读取数据时,VARCHAR总是如实取出之前存入的值(如果存储时尾部包含空格,就会继续保留着,不会像CHAR那样删除尾部空格)。
下面是测试验证过程。
1、测试CHAR类型
表结构:
CREATE TABLE `tchar` ( `id` int(10) unsigned NOT NULL DEFAULT '0', `c1` char(20) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
插入几条记录:
insert into tchar values (1, concat('a', repeat(' ',19))); insert into tchar values (2, concat(' ', repeat('a',19))); insert into tchar values (3, 'a'); insert into tchar values (4, ' '); insert into tchar values (5, '');
本文来源gao@!dai!ma.com搞$$代^@码5网@
查看存储结构:
(1) INFIMUM record offset:99 heapno:0 ... (2) SUPREMUM record offset:112 heapno:1 ... (3) normal record offset:126 heapno:2 ... <- id=1 (4) normal record offset:169 heapno:3 ... <- id=2 (5) normal record offset:212 heapno:4 ... <- id=3 (6) normal record offset:255 heapno:5 ... <- id=4 (7) normal record offset:298 heapno:6 ... <- id=5
看到这坨东西有点懵是不是,还记得我给你们安利过的一个工具不,看这里:innblock | InnoDB page观察利器。
可以看到,无论我们存储多长的字符串进去,每条记录实际都是占用43(169-126=43)字节。由此结论1成立。
简单说下,43字节的由来:
DB_TRX_ID, 6字节。
DB_ROLL_PTR, 7字节。
id, int, 4字节。
c1, char(20), 20字节;因为是CHAR类型,还需要额外1字节。
每条记录总是需要额外5字节头信息(row header)。
这样总的加起来就是43字节了。
再看下读取tchar表的结果:
select id,concat('000',c1,'$$$'),length(c1) from tchar ; +----+----------------------------+------------+ | id | concat('000',c1,'$$$') | length(c1) | +----+----------------------------+------------+ | 1 | 000a$$$ | 1 | <- 删除尾部空格 | 2 | 000 aaaaaaaaaaaaaaaaaaa$$$ | 20 | | 3 | 000a$$$ | 1 | | 4 | 000$$$ | 0 | <- 删除尾部空格,结果和id=5一样 | 5 | 000$$$ | 0 | +----+----------------------------+------------+
2、测试VARCHAR类型
表结构:
CREATE TABLE `tvarchar` ( `id` int(10) unsigned NOT NULL DEFAULT '0', `c1` varchar(20) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
插入几条记录:
insert into tvarchar values (1, concat('a', repeat(' ',19))); insert into tvarchar values (2, concat(' ', repeat('a',19))); insert into tvarchar values (3, 'a'); insert into tvarchar values (4, ' '); insert into tvarchar values (5, ''); insert into tvarchar values (6, '');
查看存储结构:
(1) INFIMUM record offset:99 heapno:0 ... (2) SUPREMUM record offset:112 heapno:1 ... (3) normal record offset:126 heapno:2 ... <- id=1 (4) normal record offset:169 heapno:3 ... <- id=2 (5) normal record offset:212 heapno:4 ... <- id=3 (6) normal record offset:236 heapno:5 ... <- id=4 (7) normal record offset:260 heapno:6 ... <- id=5 (8) normal record offset:283 heapno:7 ... <- id=6