版权声明:开源交流,可以不进行特殊介绍,但请尊重个人劳动成果,互相交流哦! https://blog.csdn.net/wanglizheng825034277/article/details/50404027
1、MySQL之char、varchar和text的设计:
(1)char(n)和varchar(n)括号中n代表字符的个数,并不代表字节个数,所以当时用了中文的时候(utf8)意味着可以插入m个中文,但是实际会占用m*3个字节
(2)char和varchar的区别在于char不管存入的值value实际占用多少个字节都会占用n个字符的空间,而varchar只会占用实际字符占用空间+1,并且实际空间+1<=n
(3)超过char和varchar的n设置后,字符串会被截断(但在代码中如果不进行判断直接插入会导致数据过长错误)
(4)char存储的时候回截断尾部的空格,varchar和text不会
(5)varchar会使用1-3个字节来存储长度,text不会
总体来说:
(1)char,定长,速度快,存在空间浪费可能,会处理尾部空格,上线255(一般不用)
(2)varchar,变长,速度慢,不存在空间浪费,不处理尾部空格,自从5.0.3版本后,上限从255扩展为65535(但因为会使用1-3个字节存储长度)
(3)text,变长大数据,速度慢,不存在空间浪费,不处理尾部空格,闪现65535,会使用额外空间存放数据长度
场景问题:(varchar后的n值很大时)
(1)空间方面:
官方规则:大于255时,varchar变为tinytext;大于500时,变为text;大于20000变为mediumtext(过大的内容使用varchar和text没有太大区别)
性能:索引是影响性能的关键因素,而text只能添加前缀索引,并且前缀索引最大只能达到1000字节;varchar由于innodb自身问题,索引长度超长会自动截断;(两者没有太大区别)
注:当长度超过255的长度后,使用varchar和text没有太大的本质区别,仅仅需要考虑下两个类型的特性即可。(text没有默认值)但仍然建议使用varchar,本着short isbetter原则,而且varchar会自动截断,不会因为code问题存入大量不合法数据。
各个字段类型的存储需求:
DataType | TINYINT | SMALLINT | MEDIUMINT | INT,INTEGER | BIGINT | FLOAT(p) | FLOAT | DOUBLE[PRECISION准确度],REAL | DECIMAL(M,D),NUMERIC(M,D) | BIT(M) |
Storage Required(bytes) | 1 | 2 | 3 | 4 | 8 | 4 if 0 <= p <=24,8 if 25 <=p <=53 | 4 | 8 | varies; | approximattely(M+7) /8 |
DataType | year | date | time | datetime | timestamp |
Storage required before mysql 5.6.4 | 1 | 3 | 3 | 8 | 4 |
Storage required as of mysql 5.6.4 | 1 | 3 | 3 + fractional seconds storage | 5+fractional seconds storage | 4+fractional seconds storage |
Date 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 |
binary(m) | M bytes, 0 <= M <= 255 |
VARCHAR(L),VARBINARY(L) | L + 1 bytes if column values require 0 – 255 bytes, L + 2 bytes if values may require more than 255 bytes |
tinyblob,tinytext | L + 1 ,where L < 28 |
blob,text | L+2 bytes, where L < 216 |
longblob,longtext | L+3 bytes, where L < 224 |
enum('value1','value2'.....) | 1 or 2 bytes depending on the number of enumeration values(65535 values maximum) |
set('value1','value2',......) | 1,2,3,4 or 8 bytes, depending on the number of set members(64 members maximum) |
可以自己看官方文档来提高自己的能力,大家一起加油!