今天群里有人问:mysql
varchar 不是最大应该只能够设置65532(第一个字节+两个长度字节)吗 ,可是为何能够设置成65533
不事后来群里有人给了解释,忽然才发现原来事情不是这么简单sql
MYSQL COMPACT格式,每条记录有一个字节来表示NULL字段分布,若是表中有字段容许为空,则最大只能定到65532,若是没有字段容许为空,则那个字节能够节省,最大能够定义到65533,不知道是否是这个缘由
在本地作了下实验,innodb+latin的环境shell
-- 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; create table test(name varchar(65533))engine=innodb DEFAULT CHARSET=latin1
对于第二种状况,容许空字段的时候是不能加到65533的长度的,最大只能到65532,到底应该是引文的那种说法。
网上也有人作了相似的实验,参考http://stackoverflow.com/questions/8295131/best-practise-for-sql-varchar-column-lengthcode
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
总结一下,原来mysql的vachar字段的类型虽然最大长度是65535,可是并非能存这么多数据,最大能够到65533(不容许非空字段的时候),当容许非空字段的时候只能到65532,。get