-- success drop table if exists test; create table test(name varchar(65533) not null)engine=innodb DEFAULT CHARSET=latin1 -- too large drop table if exists test;
name varchar(100) not null will be 1 byte (length) + up to 100 chars (latin1) name varchar(500) not null will be 2 bytes (length) + up to 500 chars (latin1) name varchar(65533) not null will be 2 bytes (length) + up to 65533 chars (latin1) name varchar(65532) will be 2 bytes (length) + up to 65532 chars (latin1) + 1 null byte
1、限制规则 字段的限制在字段定义的时候有以下规则: a) 存储限制 varchar 字段是将实际内容单独存储在聚簇索引之外,内容开头用1到2个字节表示实际长度(长度超过255时需要2个字节),因此最大长度不能超过65535。 b) 编码长度限制 字符类型若为gbk,每个字符最多占2个字节,最大长度不能超过32766; 字符类型若为utf8,每个字符最多占3个字节,最大长度不能超过21845。 对于英文比较多的论坛 ,使用GBK则每个字符占用2个字节,而使用UTF-8英文却只占一个字节。 若定义的时候超过上述限制,则varchar字段会被强行转为text类型,并产生warning。 c) 行长度限制 导致实际应用中varchar长度限制的是一个行定义的长度。 MySQL要求一个行的定义长度不能超过65535。若定义的表长度超过这个值,则提示 ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs。 2、计算例子 举两个例说明一下实际长度的计算。 a) 若一个表只有一个varchar类型,如定义为 create table t4(c varchar(N)) charset=gbk; 则此处N的最大值为(65535-1-2)/2= 32766。 减1的原因是实际行存储从第二个字节开始'; 减2的原因是varchar头部的2个字节表示长度; 除2的原因是字符编码是gbk。