關(guān)于數(shù)據(jù)庫(kù)優(yōu)化,網(wǎng)上有不少資料和方法,但是不少質(zhì)量參差不齊,有些總結(jié)的不夠到位,內(nèi)容冗雜。這篇文章就來(lái)給大家詳細(xì)介紹了26條優(yōu)化建議,下面來(lái)一起看看吧
反例:
select * from student;
正例:
select id,name, age from student;
理由:
理由:
3. 禁止使用不含字段列表的 insert 語(yǔ)句
反例:
insert into values ('a', 'b', 'c');
正例:
insert into t(a, b, c) values ('a','b','c');
理由:
案例:新建一個(gè)user表,它有一個(gè)普通索引userId,表結(jié)構(gòu)如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `age` int(11) NOT NULL, `name` varchar(30) NOT NULL, PRIMARY KEY (`id`), KEY `idx_userId` (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
查詢userid為1 或者 年齡為 18 歲的用戶
反例:
select id, user_id, age, name from user where userid=1 or age =18
正例:
# 使用union all select id, user_id, age, name from user where userid=1 union all select * from user where age = 18 # 或者分開(kāi)兩條sql寫 select id, user_id, age, name from user where userid=1; select * from user where age = 18
理由:
假設(shè) id 為 int 類型,查詢 id = 1 的數(shù)據(jù)
反例:
select id, name from student where id = '1';
正例:
select id, name from student where id = 1;
理由:
假設(shè) user 表的 age 字段,加了索引,對(duì)其進(jìn)行數(shù)據(jù)查詢
反例:
select name, age from user where age - 1 = 20;
正例:
select name, age from user where age = 21;
理由:
(Mysql中適用)
反例:
select age,name from user where age > 18;
正例:
# 可以考慮分開(kāi)兩條sql寫 select age,name from user where age 18; select age,name from user where age > 18;
理由:
反例:
select name, age, address from user where address ='深圳' order by age ;
正例:添加索引再查詢
alter table user add index idx_address_age (address,age)
反例:(這種會(huì)全查所有數(shù)據(jù))
select user_id, name, age from user where age is not null;
正例:
# 表字段age設(shè)置0為默認(rèn)值代替null select user_id, name, age from user where age > 0; 1 2
理由:
假設(shè)現(xiàn)在有student學(xué)生表,要找出一個(gè)名字叫 Tom 的人.
CREATE TABLE `student` ( `id` int(11) NOT NULL, `name` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, `date` datetime DEFAULT NULL, `sex` int(1) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
反例:
select id,name from student where name='Tom '
正例
select id,name from employee where name='Tom ' limit 1;
理由:
加上 limit 1 分頁(yè)后,只要找到了對(duì)應(yīng)的一條記錄,就不會(huì)繼續(xù)向下掃描了,效率將會(huì)大大提高。
如果name是唯一索引的話,是不必要加上 limit 1 了,因?yàn)閘imit的存在主要就是為了防止全表掃描,從而提高性能,如果一個(gè)語(yǔ)句本身可以預(yù)知不用全表掃描,有沒(méi)有l(wèi)imit ,性能的差別并不大。
我們?nèi)粘W龇猪?yè)需求時(shí),一般會(huì)用 limit 實(shí)現(xiàn),但是當(dāng)偏移量特別大的時(shí)候,查詢效率就變得低下
反例:
select id,name,age from student limit 10000,10
正例:
# 方案一 :返回上次查詢的最大記錄(偏移量) select id,name from student where id > 10000 limit 10;
# 方案二:order by + 索引 select id,name from student order by id limit 10000,10;
# 方案三:在業(yè)務(wù)允許的情況下限制頁(yè)數(shù):
理由:
假設(shè)業(yè)務(wù)需求是,用戶請(qǐng)求查看自己最近一年觀看過(guò)的電影數(shù)據(jù)。
反例:
# 一次性查詢所有數(shù)據(jù)回來(lái) select * from LivingInfo where watchId =useId and watchTime >= Date_sub(now(),Interval 1 Y)
正例:
# 分頁(yè)查詢 select * from LivingInfo where watchId =useId and watchTime>= Date_sub(now(),Interval 1 Y) limit offset,pageSize # 如果是前端分頁(yè),可以先查詢前兩百條記錄,因?yàn)橐话阌脩魬?yīng)該也不會(huì)往下翻太多頁(yè) select * from LivingInfo where watchId =useId and watchTime>= Date_sub(now(),Interval 1 Y) limit 200 ;
當(dāng)用到模糊關(guān)鍵字查詢使用 like 時(shí),like很可能讓索引失效。
反例:
SELECT * FROM student WHERE name LIKE '%strive_day'; -- 或者使用 % 包裹 SELECT * FROM student WHERE name LIKE '%strive_day%';
正例:
SELECT * FROM student WHERE name LIKE 'strive_day%';
理由:
案例:查詢最近七天內(nèi)登陸過(guò)的用戶(假設(shè) loginTime 字段加了索引)
反例:
SELECT * FROM system_user user WHERE Date_ADD(user.loginTime,Interval 7 DAY) >= now();
正例:
SELECT * FROM system_user user WHERE user.loginTime >=Date_ADD(NOW(),INTERVAL - 7 DAY);
理由:
假設(shè)有一個(gè)聯(lián)合索引 (user_id, age),user_id 在前,age 在后。
反例:
select user_id, name, age from user where age = 10;
正例:
# 符合最左匹配原則 select user_id, name, age from user where userid = 1 and age = 21; # 符合最左匹配原則 select user_id, name, age from user where userid = 1;
理由:
覆蓋索引能夠使得你的SQL語(yǔ)句不需要 回表,僅僅訪問(wèn)索引就能夠得到所有需要的數(shù)據(jù),大大提高了查詢效率。
反例:
# like模糊查詢,不走索引 select user_id, name, age from user where user_id like '%123%'
# id為主鍵,那么為普通索引,即覆蓋索引。 select user_id, name, age from user where userid like '%123%';
反例:
KEY `idx_userId` (`userId`) KEY `idx_userId_age` (`userId`,`age`)
正例:
KEY `idx_userId_age` (`userId`,`age`) # 刪除 userId 的索引(KEY `idx_userId_age` (`userId`,`age`)) # 因?yàn)榻M合索引(A,B)相當(dāng)于創(chuàng)建了(A)和(A,B)索引。
理由:
Inner join 內(nèi)連接,在兩張表進(jìn)行連接查詢時(shí),只保留兩張表中完全匹配的結(jié)果集
left join 在兩張表進(jìn)行連接查詢時(shí),會(huì)返回左表所有的行,即使在右表中沒(méi)有匹配的記錄。
right join 在兩張表進(jìn)行連接查詢時(shí),會(huì)返回右表所有的行,即使在左表中沒(méi)有匹配的記錄。
都滿足SQL需求的前提下,優(yōu)先使用Inner join(內(nèi)連接),如果要使用left join,左邊表數(shù)據(jù)結(jié)果盡量小,如果有條件的盡量放到左邊處理。
反例:
select name, age from tab1 t1 left join tab2 t2 on t1.age = t2.age where t1.id = 2;
正例:
select name, age from (select * from tab1 where id = 2) t1 left join tab2 t2 on t1.age = t2.age;
理由:
反例:
for(User u :list) { INSERT into user(name,age) values(name, age)}
正例:
//一次500批量插入,分批進(jìn)行 insert into user(name,age) values foreach collection="list" item="item" index="index" separator=","> (#{item.name},#{item.age}) /foreach>
理由:
distinct 關(guān)鍵字一般用來(lái)過(guò)濾重復(fù)記錄,以返回不重復(fù)的記錄。在查詢一個(gè)字段或者很少字段的情況下使用時(shí),給查詢帶來(lái)優(yōu)化效果。但是在字段很多的時(shí)候使用,卻會(huì)大大降低查詢效率。
反例:
# 去重多個(gè)字段 SELECT DISTINCT * from user;
正例:
select DISTINCT name from user;
理由:
理由:
數(shù)據(jù)量大的時(shí)候,需要避免同時(shí)修改或刪除過(guò)多數(shù)據(jù),同時(shí)會(huì)造成cpu利用率過(guò)高,從而影響別人對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)。
反例:
# 一次刪除10萬(wàn)或者100萬(wàn)+條數(shù)據(jù) delete from user where id 1000000; # 或者采用單一循環(huán)操作,效率低,時(shí)間漫長(zhǎng) for(User user:list){delete from user;}
正例:
# 分批進(jìn)行刪除,如每次500 delete user where id 500 delete user where id >= 500 and id 1000; ... delete user where id >= 999500 and id 1000000;
理由:
假設(shè)表A表示某企業(yè)的員工表,表B表示部門表,查詢所有部門的所有員工SQL
反例::
select * from A where deptId in (select deptId from B);
這樣寫等價(jià)于:
先查詢部門表B
select deptId from B
再由部門deptId,查詢A的員工
select * from A where A.deptId = B.deptId
可以抽象成這樣的一個(gè)循環(huán)語(yǔ)句:
List> resultSet ; for(int i = 0; i B.length; i ++) { for(int j = 0; j A.length; j ++) { if(A[i].id == B[j].id) { resultSet.add(A[i]); break; } } }
我們也可以用exists實(shí)現(xiàn)一樣的查詢功能
select * from A where exists (select 1 from B where A.deptId = B.deptId);
上述代碼等價(jià)于:
select * from A,先從A表做循環(huán)
select * from B where A.deptId = B.deptId,再?gòu)腂表做循環(huán).
因?yàn)閑xists查詢的理解就是,先執(zhí)行主查詢,獲得數(shù)據(jù)后,再放到子查詢中做條件驗(yàn)證,根據(jù)驗(yàn)證結(jié)果(true或者false),來(lái)決定主查詢的數(shù)據(jù)結(jié)果是否得以保留。
同理,可以抽象成這樣一個(gè)循環(huán):
List> resultSet; for(int i = 0; i A.length; i ++) { for(int j = 0; j B.length; j ++) { if(A[i].deptId == B[j].deptId) { resultSet.add(A[i]); break; } } }
理由:
反例:
`king_id` varchar(20) NOT NULL COMMENT '123'
正例:
`king_id` int(11) NOT NULL COMMENT '123'
理由:
如果檢索結(jié)果中不會(huì)有重復(fù)的記錄,推薦 union all 替換 union
反例:
select * from user where userid = 1 union select * from user where age = 20
正例:
select * from user where userid = 1 union all select * from user where age = 20
理由:
反例:
select * from user where userid = 1;
正例:
select * from user where userid ='1';
理由:
第一條語(yǔ)句未加單引號(hào)就不走索引,這是因?yàn)椴患訂我?hào)時(shí),是字符串跟數(shù)字的比較,它們類型不匹配,MySQL會(huì)做隱式的類型轉(zhuǎn)換,把它們轉(zhuǎn)換為浮點(diǎn)數(shù)再做比較。
到此這篇關(guān)于MySQL優(yōu)化之如何寫出高質(zhì)量sql語(yǔ)句的文章就介紹到這了,更多相關(guān)MySQL優(yōu)化sql語(yǔ)句內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:南充 麗水 自貢 西寧 無(wú)錫 迪慶 龍巖 徐州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《MySQL優(yōu)化之如何寫出高質(zhì)量sql語(yǔ)句》,本文關(guān)鍵詞 MySQL,優(yōu)化,之,如何,寫出,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。