SQL優化的解決方案

2021-10-07 07:47:55 字數 1479 閱讀 7097

該type列 explain輸出介紹如何連線表。在json格式的輸出中,這些作為access_type屬性的值找到。以下列表描述了連線型別,從最佳型別到最差型別:

system > const > eq_ref > ref > range > index > all

以下是乙個示例,我們要盡量避免出現下例情況

1.sql優化我們記一件事就是盡量避免使用全表掃瞄,如上圖

2.我們在查詢時經常使用的where的字段一定要加索引

select * from table where number=1
這裡的number如果使用次數多就加乙個索引

3.在查詢時盡量不要使用 in 如果是連續值請用between

不要使用這種 select * from table1 where  number in(1,2,3)

;使用這種 select * from table1 where number between 1 and 3;

4.查詢的時候不要在where後面加表示式

不要用 select * from table1 where  number/2 =1;

使用 select * from table1 where number =1*2;

5.查詢的時候不要用select * ,用到哪個字段查哪個

不要使用 select * from table;

使用 select number from table;

6.不要用where 1=1,字串拼接的時候去判斷

不要使用 select * from table where 1=1 and number=1;

使用 select * from table number=1;

7.查詢用到 like的時候,不要把%放前面,就是說最好已知字串開頭用字串的開頭去匹配後面的字段,有索引的情況下『%張』查詢時間 是 『張%』查詢時間的幾何倍數,比如幾十幾百倍

不用 select * from table name like '%張%'

可以用select * from table name like 『張%』

8.不要頻繁建立刪除臨時表,這樣挺消耗系統資源的

9.資料量大的話建表時不要建索引,等所有資料入庫後建索引

10.建表字段一定要合理,不用預設值為null,能用值型別就用值型別

SQL注入解決方案

sql作為字串通過api傳入給資料庫,資料庫將查詢的結果返回,資料庫自身是無法分辨傳入的sql是合法的還是不合法的,它完全信任傳入的資料,如果傳入的sql語句被惡意使用者控制或者篡改,將導致資料庫以當前呼叫者的身份執行預期之外的命令並且返回結果,導致安全問題。根據相關技術原理,sql注入可以分為平台...

SQL 排序的解決方案

現有規則 a,b,c,d 現有順序 a1 b1 空 空 a1 b1 空 d1 a1 b1 c1 空 期望順序 a1 b1 空 空 a1 b1 c1 空 a1 b1 空 d1 解答 名稱 解決排序問題 declare t table a char 10 b char 10 c char 10 d ch...

SQL 常用sql分頁解決方案

分頁方案一 利用not in和select top分頁 語句形式 select top10 from testtable where id notin select top20 idfrom testtable order byid order byid select top頁大小 from tes...