MySQL優化索引之三表優化

2021-10-05 17:55:36 字數 2069 閱讀 9664

建表sql

create table if not exists `phone`(

`phoneid` int(10) unsigned not null primary key auto_increment,

`card` int (10) unsigned not null

)engine = innodb;

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

insert into phone(card)values(floor(1+(rand()*20)));

drop index y on class;
需求:三表左連線我們先來看看執行計畫

explain select * from class left join book on class.card=book.card left join phone on book.card = phone.card;
可以看到全是all查詢,效率非常低 

解決方案是給後兩個表的字段加索引,永遠記住小表驅動大表

alter table `phone` add index z(`card`);

alter table `book` add index y(`card`);

再次檢視執行計畫

可以看到效能提公升非常明顯 

MySQL索引優化(索引三表優化案例)

建表sql phone book表建立索引 1 保證被驅動表的join欄位已經被索引 被驅動表 join 後的表為被驅動表 需要被查詢 2 left join 時,選擇小表作為驅動表,大表作為被驅動表。但是 left join 時一定是左邊是驅動表,右邊是被驅動表 3 inner join 時,my...

MySQL索引優化(索引三表優化案例)

建表sql phone book表建立索引 1 保證被驅動表的join欄位已經被索引 被驅動表 join 後的表為被驅動表 需要被查詢 2 left join 時,選擇小表作為驅動表,大表作為被驅動表。但是 left join 時一定是左邊是驅動表,右邊是被驅動表 3 inner join 時,my...

MySQL 資料庫效能優化之(三)索引優化

大家都知道索引對於資料訪問的效能有非常關鍵的作用,都知道索引可以提高資料訪問效率。為什麼索引能提高資料訪問效能?他會不會有 是不是索引建立越多,效能就越好?到底該如何設計索引,才能最大限度的發揮其效能?這篇文章主要是帶著上面這幾個問題來做乙個簡要的分析,同時排除了業務場景所帶來的特殊性,請不要糾結業...