慢SQL消耗了70%~90%的數(shù)據(jù)庫(kù)CPU資源; SQL語(yǔ)句獨(dú)立于程序設(shè)計(jì)邏輯,相對(duì)于對(duì)程序源代碼的優(yōu)化,對(duì)SQL語(yǔ)句的優(yōu)化在時(shí)間成本和風(fēng)險(xiǎn)上的代價(jià)都很低; SQL語(yǔ)句可以有不同的寫(xiě)法;
下面是 賀春旸老師 總結(jié)的一些SQL常見(jiàn)的優(yōu)化方法,每個(gè)案例都簡(jiǎn)單易懂,在開(kāi)發(fā)過(guò)程中可以作為參考:
例:SELECT * FROM t1 WHERE id (SELECT id FROM t2 WHERE name='hechunyang');
子查詢(xún)?cè)贛ySQL5.5版本里,內(nèi)部執(zhí)行計(jì)劃器是這樣執(zhí)行的:先查外表再匹配內(nèi)表,而不是先查內(nèi)表t2,當(dāng)外表的數(shù)據(jù)很大時(shí),查詢(xún)速度會(huì)非常慢。
在MariaDB10/MySQL5.6版本里,采用join關(guān)聯(lián)方式對(duì)其進(jìn)行了優(yōu)化,這條SQL會(huì)自動(dòng)轉(zhuǎn)換為 SELECT t1.* FROM t1 JOIN t2 ON t1.id = t2.id;
但請(qǐng)注意的是:優(yōu)化只針對(duì)SELECT有效,對(duì)UPDATE/DELETE子查詢(xún)無(wú)效,固生產(chǎn)環(huán)境應(yīng)避免使用子查詢(xún)
例:SELECT * FROM t WHERE YEAR(d) >= 2016; 由于MySQL不像Oracle那樣支持函數(shù)索引,即使d字段有索引,也會(huì)直接全表掃描。 應(yīng)改為-----> SELECT * FROM t WHERE d >= '2016-01-01';
低效查詢(xún) SELECT * FROM t WHERE LOC_ID = 10 OR LOC_ID = 20 OR LOC_ID = 30; -----> 高效查詢(xún) SELECT * FROM t WHERE LOC_IN IN (10,20,30);
SELECT * FROM t WHERE name LIKE '%de%'; -----> SELECT * FROM t WHERE name LIKE 'de%'; 目前只有MySQL5.7支持全文索引(支持中文)
讀取適當(dāng)?shù)挠涗汱IMIT M,NSELECT * FROM t WHERE 1; -----> SELECT * FROM t WHERE 1 LIMIT 10;
SELECT * FROM t WHERE id = '19'; -----> SELECT * FROM t WHERE id = 19;
SELECT goods_id,count(*) FROM t GROUP BY goods_id; 默認(rèn)情況下,MySQL對(duì)所有GROUP BY col1,col2...的字段進(jìn)行排序。如果查詢(xún)包括GROUP BY,想要避免排序結(jié)果的消耗,則可以指定ORDER BY NULL禁止排序。 -----> SELECT goods_id,count(*) FROM t GROUP BY goods_id ORDER BY NULL;
SELECT * FROM t1 WHERE 1=1 ORDER BY RAND() LIMIT 4; MySQL不支持函數(shù)索引,會(huì)導(dǎo)致全表掃描 -----> SELECT * FROM t1 WHERE id >= CEIL(RAND()*1000) LIMIT 4;
SELECT count(1) FROM user u LEFT JOIN user_info i ON u.id = i.user_id WHERE 1 = 1 ORDER BY u.create_time DESC; -----> SELECT count(1) FROM user u LEFT JOIN user_info i ON u.id = i.user_id;
INSERT INTO t (id, name) VALUES(1,'Bea'); INSERT INTO t (id, name) VALUES(2,'Belle'); INSERT INTO t (id, name) VALUES(3,'Bernice'); -----> INSERT INTO t (id, name) VALUES(1,'Bea'), (2,'Belle'),(3,'Bernice');
作者:賀春旸(51CTO博客專(zhuān)家)
|