1. 程式人生 > >10.18 資料庫之索引優化方案

10.18 資料庫之索引優化方案

        索引
            作用:約束+加速查詢
                普通索引
                    create index ix_name on 表名(欄位)
                    作用:加速查詢
                    
                唯一索引:
                    作用:約束和加速查詢
                create unique index un_index_name on big_data(email)
                
                主鍵索引
                
                #覆蓋索引:在索引檔案中直接獲取資料
                    例如:
                    
select name from big_data where name = 'alex50000'; #索引合併:把多個單列索引一起使用 select * from big_data where name = 'alex13131' and id = 13131; #聯合索引: 聯合普通索引 聯合唯一索引 聯合主鍵索引
select * from big_data where name = 'alex13131' and id = 13131; # 最左字首 如果使用組合索引如上,name和email組合索引之後,查詢 (1)name和email ---使用索引 (2)name ---使用索引 (3)email ---不適用索引 對於同時搜尋n個條件時,組合索引的效能好於多個單列索引         
******組合索引的效能>索引合併的效能********* 對於索引 1.建立索引 注意事項: (1)避免使用select * (2)count(1)或count(列) 代替count(*) (3)建立表時儘量使用char代替varchar (4)表的欄位順序固定長度的欄位優先 (5)組合索引代替多個單列索引(經常使用多個條件查詢時) (6)儘量使用短索引 (create index ix_title on tb(title(16));特殊的資料型別 text型別) (7)使用連線(join)來代替子查詢 (8)連表時注意條件型別需一致 (9)索引雜湊(重複少)不適用於建索引,例如:性別不合適 2.命中索引 3.正確使用索引 注意事項: - like '%xx' select * from userinfo where name like '%al'; - 使用函式 select * from userinfo where reverse(name) = 'alex333'; - or select * from userinfo where id = 1 or email = '[email protected]'; 特別的:當or條件中有未建立索引的列才失效,以下會走索引 select * from userinfo where id = 1 or name = 'alex1222'; select * from userinfo where id = 1 or email = '[email protected]' and name = 'alex112' - 型別不一致 如果列是字串型別,傳入條件是必須用引號引起來,不然... select * from userinfo where name = 999; - != select count(*) from userinfo where name != 'alex' 特別的:如果是主鍵,則還是會走索引 select count(*) from userinfo where id != 123 - > select * from userinfo where name > 'alex' 特別的:如果是主鍵或索引是整數型別,則還是會走索引 select * from userinfo where id > 123 select * from userinfo where num > 123 - order by select email from userinfo order by name desc; 當根據索引排序時候,選擇的對映如果不是索引,則不走索引 特別的:如果對主鍵排序,則還是走索引: select * from userinfo order by nid desc; - 組合索引最左字首 如果組合索引為:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引 對於建立索引,它是真實存在的,佔用硬碟空間,儘量不要使用索引 select * from big_data where id > 2000010 limit 10; select * from (select * from big_data where id > 2000020 limit 30) as A order by id desc limit 10;