mysql varchar 非空判断_工资从1万到3万,你还差mysql数据库优化之系列三
生活随笔
收集整理的這篇文章主要介紹了
mysql varchar 非空判断_工资从1万到3万,你还差mysql数据库优化之系列三
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
查詢性能的優化
優化查詢分析的步驟:
1.應用查詢是否檢索超過需要的數據
2.mysql服務器是否在分析超過需要的數據
正確使用索引:
1.like語句操作
一般不使用%或_開頭例如: select * from tableName where name like '%cn';只能使用like 'aaa%';2.組合索引
例如索引index index_name (a, b, c) 只支持a 或 a, b 或 a, b, c者三種組合,不支持b,c, 最左前綴3.避免在where子句中對null進行判斷
例如:select id from t where num is null修改:可以num上設置默認值為0select id from t where num=0;4.盡量避免使用where子句使用!=,<>,or
5.in和not in也要謹慎使用
例如:select id from t where num in(1,2,3);修改:對于連續的數值,可以使用betweenselect id from t where num between 1 and 3;6.如果在where子句中使用參數,也會導致全表掃描
mysql在運行時候才會解析變量,sql語句的優化在編譯的時候就進行了,但是編譯的時候這個變量還是未知的例如: select id from t where num=@num;修改:強制使用索引select id from t with(index(索引名)) where num=@num;7.盡量避免在where子句的=左面進行運算
例如:select id from t where num/2=100;修改:select id from t where num = 100*2;例如:select id from t where substring(name, 1, 3)='abc';修改:select id from t where name like 'abc%';其他的優化點:
1.盡量使用數字類型的字段
2.把ip存儲為unsigned int
使用int類型4個字節,比char/varchar更節省空間,查詢時候也會占用優勢3.在join表要使用相當類型的列,并將其建立索引
例如:select * from users left join company on users.state=company.state兩個state都要建立索引,并且使用相當類型,使用相同的字符集4.盡量避免使用order by rand()
例子: explain select * from test order by rand();5.避免使用select *
6.一定要為每張表設置id為主鍵,最好是int類型,并且最好設置auto_increment
7.優化count()查詢
統計某列值的數量,要求列值為非空,也就是不會統計null統計行數如果確定count()沒有空值,實際是在統計行數統計行數時候直接使用count(*)8.不要添加冗余或者是重復索引,刪除長期不用的索引
例如:創建了聯合索引(A,B), 不要再單獨為(A)創建索引9.盡量避免使用游標,因為通常情況下游標的效率比較差
10.盡量避免大事務操作,會降低并發性能
11.優化or條件
例如:create table test6(id int not null,name varchar(20) not null,index index_id (id),index index_name(name))插入數據:insert into test6 values(1, 'zhangsan');insert into test6 values(2, 'lisi');使用or查詢:explain select * from test6 where id=1 or name='lisi';使用union all優化explain select * from test6 where id=1 union all select * from test6 where name='lisi';12.優化分頁查詢(limit)
例子:創建表:create table test7(id int not null,username varchar(16) not null,index index_id(id))插入100000條數據的函數:DELIMITER #CREATE PROCEDURE pro2()BEGIN DECLARE i INT DEFAULT 0; WHILE i<10000 DO INSERT INTO test7 VALUES(i, CONCAT('aa', i)); SET i=i+1; END WHILE;END #調用函數CALL pro2();分頁查詢數據:explain select * from test7 order by id limit 1000, 20;優化:explain select * from test7 inner join (select id from test7 order by id limit 1000, 20) as o using(id);上面的優化可以改寫為:explain select * from test7 t inner join (select id from test7 order by id limit 1000, 20) as o on t.id=o.id;總結
以上是生活随笔為你收集整理的mysql varchar 非空判断_工资从1万到3万,你还差mysql数据库优化之系列三的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阴阳师须佐之男技能是什么 阴阳师须佐之男
- 下一篇: mysql查询并设置高亮_慢查询分析调优