MySQl之char,varchar,text
阿新 • • 發佈:2018-11-23
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 |
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) |
可以自己看官方文件來提高自己的能力,大家一起加油!