1)varchar与char的区别
- 固定长度 (char) 或可变长度 (varchar) 字符数据类型。
Varchar存储可变长字符串,小于255字节时需要1个额外字节(大于255需要2个额外字节)存储长度,最大长度为65532字节(所有列总和);
char存储定长(right padding),读取时会截断末尾空格,长度最大为255字符;
最大存储30个字符;varchar(5)和(200)存储hello所占空间一样,但后者在排序时会消耗更多内存,因为order by col采用fixed_length计算col长度(memory引擎也一样)
Data Type | Storage Required |
CHAR(M) | M × w bytes, 0 <= M <= 255, where w is the number of bytes required for the maximum-length character in the character set. See<span color:#015a84;"="" style="word-wrap: break-word; font-size: 10pt;">Section 14.5.13.6, “Physical Row Structure” for information about CHARdata type storage requirements for InnoDB tables. |
BINARY(M) | M bytes, 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)存储和计算均一样;
此文章转载于http://blog.itpub.net/15480802/viewspace-1330966/