mysql stack is full_mysql优化之表的优化与列类型选择
表的優(yōu)化與列類型選擇
列選取原則####
1、字段類型優(yōu)先級
整型 > date,time > char,varchar > blob
因?yàn)?整型,time運(yùn)算快,節(jié)省空間,char/varchar要考慮字符集的轉(zhuǎn)換與排序時(shí)的校對集,速度慢,blob無法使用內(nèi)存臨時(shí)表
列的特點(diǎn)分析:
整型: 定長,沒有國家/地區(qū)之分,沒有字符集的差異
time: 定長,運(yùn)算快,節(jié)省空間. 考慮時(shí)區(qū),寫sql時(shí)不方便 where > ‘2005-10-12’;
enum: 能起來約束值的目的, 內(nèi)部用整型來存儲(chǔ),但與char聯(lián)查時(shí),內(nèi)部要經(jīng)歷串與值的轉(zhuǎn)化
char: 定長, 考慮字符集和(排序)校對集
varchar: 變長 要考慮字符集的轉(zhuǎn)換與排序時(shí)的校對集,速度慢.
text/Blob:無法使用內(nèi)存臨時(shí)表
2、長度夠用就行,不要慷慨(如smallint,varchar(N))
大的字段浪費(fèi)內(nèi)存,影響速度
以年齡為例 tinyint unsigned not null ,可以存儲(chǔ)255歲,足夠. 用int浪費(fèi)了3個(gè)字節(jié)
以varchar(10) ,varchar(300)存儲(chǔ)的內(nèi)容相同, 但在表聯(lián)查時(shí),varchar(300)要花更多內(nèi)存
3、盡量避免使用null
null不利于索引,要用特殊的字節(jié)來標(biāo)注,在磁盤上占據(jù)的空間其實(shí)很大
實(shí)驗(yàn):
建立兩張字段相同的表,一個(gè)允許為null,一個(gè)不允許為null,錄入相同的數(shù)據(jù),使用explain查看索引文件的大小
create table t3(
-> name char(1) not null default '',
-> key(name)
-> )engine myisam charset utf8;
create table t4(
-> name char(1),
-> key(name)
-> )engine myisam charset utf8;
insert into t3 values('a'),('');
insert into t4 values('a'),(null);
explain select * from t3 where name='a';
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t3
type: ref
possible_keys: name
key: name
key_len: 3
ref: const
rows: 1
Extra: Using where; Using index
1 row in set (0.03 sec)
explain select * from t4 where name='a';
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t4
type: ref
possible_keys: name
key: name
key_len: 4
ref: const
rows: 1
Extra: Using where; Using index
1 row in set (0.00 sec)
比較兩張表的key_len,可以發(fā)現(xiàn)允許null值的t4表的key_len要長于t3表,這是因?yàn)槭褂胣ull之后,表要多儲(chǔ)存一個(gè)字節(jié),用來區(qū)分是否是null,另外null所占用的空間較大。
**還有一點(diǎn)就是,null不便于查詢,where 列名 = null 和 where 列名 != null 都查詢不到值,需要使用 where 列名 is null 或者 where 列名 is not null
enum列的說明
1、enum列在內(nèi)部是用整型來存儲(chǔ)的
2、enum列與enum列相關(guān)聯(lián)速度最快
3、enum列比(var)char的弱勢--在碰到與char關(guān)聯(lián)時(shí),要轉(zhuǎn)換,花費(fèi)時(shí)間
4、優(yōu)勢在于,當(dāng)char非常長時(shí),enum依然是整型固定長度,當(dāng)查詢的數(shù)據(jù)量越大時(shí),enum的優(yōu)勢越明顯
5、enum與char/varchar關(guān)聯(lián),因?yàn)橐D(zhuǎn)換,速度要比enum->enum,char->char要慢,但有時(shí)也可以這樣用--就是在數(shù)據(jù)量特別大的時(shí)候,可以節(jié)省IO
create table t5(
-> gender enum('male','female') not null default 'male'
-> )engine myisam charset utf8;
insert into t5 values('male'),('female');
+--------+
| gender |
+--------+
| male |
| female |
+--------+
select gender+0 from t5
+----------+
| gender+0 |
+----------+
| 1 |
| 2 |
+----------+
總結(jié)
以上是生活随笔為你收集整理的mysql stack is full_mysql优化之表的优化与列类型选择的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 整数_MySQL 整数(in
- 下一篇: rjdbc读取mysql_R通过RJDB