国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

8個SQL語句常用優化技巧

2024-07-21 02:53:11
字體:
來源:轉載
供稿:網友
要提高SQL語句的執行效率,最常見的方法就是建立索引,以及盡量避免全表掃描。在本章MySQL教程中,UncleToo給大家整理一些常見的SQL優化技巧,避免全表掃描。一個簡單的優化,也許能讓你的SQL執行效率提高幾倍,甚至幾十倍。1、避免在where子句中使用 is null 或 is not null 對字段進行判斷。如:select id from table where name is null在這個查詢中,就算我們為 name 字段設置了索引,查詢分析器也不會使用,因此查詢效率底下。為了避免這樣的查詢,在數據庫設計的時候,盡量將可能會出現 null 值的字段設置默認值,這里如果我們將 name 字段的默認值設置為0,那么我們就可以這樣查詢:select id from table where name = 0

2、避免在 where 子句中使用 or來鏈接條件。如:select id from table where name = 'UncleToo' or name = 'php'這種情況,我們可以這樣寫:select id from table where name = 'UncleToo'union allselect id from table where name = 'PHP'

3、避免在 where 子句中使用 != 或 <> 操作符。如:select name from table where id <> 0數據庫在查詢時,對 != 或 <> 操作符不會使用索引,而對于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,數據庫才會使用索引。因此對于上面的查詢,正確寫法應該是:select name from table where id < 0union allselect name from table where id > 0 4、少用 in 或 not in。雖然對于 in 的條件會使用索引,不會全表掃描,但是在某些特定的情況,使用其他方法也許效果更好。如:select name from table where id in(1,2,3,4,5)像這種連續的數值,我們可以使用 BETWEEN AND,如:select name from table where id between 1 and 55、注意 like 中通配符的使用。下面的語句會導致全表掃描,盡量少用。如:select id from table where name like'%UncleToo%'或者select id from table where name like'%UncleToo'而下面的語句執行效率要快的多,因為它使用了索引:select id from table where name like'UncleToo%'6、避免在 where 子句中對字段進行表達式操作。如:select name from table where id/2 = 100正確的寫法應該是:select name from table where id = 100*27、避免在 where 子句中對字段進行函數操作。如:select id from table where substring(name,1,8) = 'UncleToo'或select id from table where datediff(day,datefield,'2014-07-17') >= 0這兩條語句中都對字段進行了函數處理,這樣就是的查詢分析器放棄了索引的使用。正確的寫法是這樣的:select id from table where name like'UncleToo%'或select id from table where datefield <= '2014-07-17'也就是說,不要在 where 子句中的 = 左邊進行函數、算術運算或其他表達式運算。8、在子查詢中,用 exists 代替 in 是一個好的選擇。如:select name from a where id in(select id from b) 如果我們將這條語句換成下面的寫法:select name from a where exists(select 1 from b where id = a.id)這樣,查詢出來的結果一樣,但是下面這條語句查詢的速度要快的多。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鱼台县| 枞阳县| 沙田区| 林西县| 西乌珠穆沁旗| 八宿县| 定远县| 枣庄市| 兰西县| 临泽县| 宜兰县| 龙口市| 万全县| 永修县| 黎城县| 祥云县| 平果县| 濮阳市| 大城县| 义马市| 贵德县| 永济市| 富阳市| 营山县| 日土县| 湟源县| 五家渠市| 青浦区| 武陟县| 鸡泽县| 海口市| 阳山县| 济宁市| 万山特区| 潍坊市| 光山县| 德江县| 民乐县| 巴楚县| 松桃| 固阳县|