1)varchar与char的区别
Varchar存储可变长字符串,小于255字节时需要1个额外字节(大于255需要2个额外字节)存储长度,最大长度为65532字节(所有列总和);
char存储定长(right padding),读取时会截断末尾空格,长度最大为255字符;
2)varchar(30)中30的涵义
最大存储30个字符;varchar(5)和(200)存储hello所占空间一样,但后者在排序时会消耗更多内存,因为order by col采用fixed_length计算col长度(memory引擎也一样)
Data
Type
Storage
Required
CHAR(M)
M×wbytes, 0<=M<=255, wherewis the number of bytes
required for the maximum-length character in the character set. Seefor information aboutCHARdata
type storage requirements forInnoDBtables.
BINARY(M)
Mbytes, 0<=M<=255
VARCHAR(M),VARBINARY(M)
L+ 1 bytes if column values
require 0 – 255 bytes,L+ 2 bytes if values may
require more than 255 bytes
For example, a VARCHAR(255) column can hold a string with a maximum length of 255 characters(字符而非字节). 对于latin1,’abcd’的L为4,存储需要5个字节;对于ucs2(双字节字符),则需要10个字节存储(最大长度为510>255,故需要额外2个字节)
3)int(20)中20的涵义
20表示最大显示宽度为20,但仍占4字节存储,存储范围不变;
create table int_test(a int zerofill NOT NULL auto_increment, PRIMARY KEY (a));
create table int_test_4(a int(4) zerofill NOT NULL auto_increment, PRIMARY KEY (a));
select * from int_test;
+------------+
| a |
+------------+
| 0000000001 |
| 0000000002 |
| 0000000003 |
| 2147483648 |
+------------+
select * from int_test_4;
+------------+
| a |
+------------+
| 0001 |
| 0002 |
| 0003 |
| 2147483648 |
+------------+
4)为什么MySQL这样设计?
对大多数应用没有意义,只是规定一些工具用来显示字符的个数;int(1)和int(20)存储和计算均一样;