mysql stack is full_mysql优化之表的优化与列类型选择
表的優化與列類型選擇
列選取原則####
1、字段類型優先級
整型 > date,time > char,varchar > blob
因為 整型,time運算快,節省空間,char/varchar要考慮字符集的轉換與排序時的校對集,速度慢,blob無法使用內存臨時表
列的特點分析:
整型: 定長,沒有國家/地區之分,沒有字符集的差異
time: 定長,運算快,節省空間. 考慮時區,寫sql時不方便 where > ‘2005-10-12’;
enum: 能起來約束值的目的, 內部用整型來存儲,但與char聯查時,內部要經歷串與值的轉化
char: 定長, 考慮字符集和(排序)校對集
varchar: 變長 要考慮字符集的轉換與排序時的校對集,速度慢.
text/Blob:無法使用內存臨時表
2、長度夠用就行,不要慷慨(如smallint,varchar(N))
大的字段浪費內存,影響速度
以年齡為例 tinyint unsigned not null ,可以存儲255歲,足夠. 用int浪費了3個字節
以varchar(10) ,varchar(300)存儲的內容相同, 但在表聯查時,varchar(300)要花更多內存
3、盡量避免使用null
null不利于索引,要用特殊的字節來標注,在磁盤上占據的空間其實很大
實驗:
建立兩張字段相同的表,一個允許為null,一個不允許為null,錄入相同的數據,使用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,可以發現允許null值的t4表的key_len要長于t3表,這是因為使用null之后,表要多儲存一個字節,用來區分是否是null,另外null所占用的空間較大。
**還有一點就是,null不便于查詢,where 列名 = null 和 where 列名 != null 都查詢不到值,需要使用 where 列名 is null 或者 where 列名 is not null
enum列的說明
1、enum列在內部是用整型來存儲的
2、enum列與enum列相關聯速度最快
3、enum列比(var)char的弱勢--在碰到與char關聯時,要轉換,花費時間
4、優勢在于,當char非常長時,enum依然是整型固定長度,當查詢的數據量越大時,enum的優勢越明顯
5、enum與char/varchar關聯,因為要轉換,速度要比enum->enum,char->char要慢,但有時也可以這樣用--就是在數據量特別大的時候,可以節省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 |
+----------+
總結
以上是生活随笔為你收集整理的mysql stack is full_mysql优化之表的优化与列类型选择的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 整数_MySQL 整数(in
- 下一篇: rjdbc读取mysql_R通过RJDB