MySql 多表聯合語句優化

2021-08-28 20:16:41 字數 3302 閱讀 6397

explain sql效能測試返回值的具體含義如下:

mysql>explain select * from table;
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra |table#顯示該語句涉及的表

type#這列很重要,顯示了連線使用了哪種類別,有無使用索引,反映語句的質量。

possible_keys#列指出mysql能使用哪個索引在該表中找到行

key#顯示mysql實際使用的鍵(索引)。如果沒有選擇索引,鍵是null。

key_len#顯示mysql決定使用的鍵長度。如果鍵是null,則長度為null。使用的索引的長度。在不損失精確性的情況下,長度越短越好

ref#顯示使用哪個列或常數與key一起從表中選擇行。

rows#顯示mysql認為它執行查詢時必須檢查的行數。

extra#包含mysql解決查詢的詳細資訊。

其中:explain的type顯示的是訪問型別,是較為重要的乙個指標,結果值從好到壞依次是:

system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > all(優-->差)

一般來說,得保證查詢至少達到range級別,最好能達到ref,否則就可能會出現效能問題;

多表查詢例項:

select  suser.user_id,suser.org_id,suser.identity,suser.user_loginname,suser.user_mobile,suser.insert_time,group_concat(c.card_no) user_mail, puser.user_mobile from org_user suser

left join student s on suser.user_id=s.user_id and suser.org_id=s.org_id and suser.identity=2 and suser.is_del=0 and s.is_del=0

left join card c on s.stud_id = c.stud_id

left join student2parent sp on sp.stud_id=s.stud_id and sp.is_del=0

left join parent p on p.parent_id=sp.parent_id and p.is_del=0 and p.org_id=s.org_id and p.org_id=suser.org_id

left join org_user puser on p.org_id=puser.org_id and p.user_id=puser.user_id and puser.org_id=suser.org_id and puser.org_id=s.org_id and puser.is_del=0 and puser.identity=0

where 1=1

and locate('132', puser.user_mobile)>0;

查詢的結果:18.969

使用explain檢視執行計畫:

explain 

select suser.user_id,suser.org_id,suser.identity,suser.user_loginname,suser.user_mobile,suser.insert_time,group_concat(c.card_no) user_mail, puser.user_mobile from org_user suser

left join student s on suser.user_id=s.user_id and suser.org_id=s.org_id and suser.identity=2 and suser.is_del=0 and s.is_del=0

left join card c on s.stud_id = c.stud_id

left join student2parent sp on sp.stud_id=s.stud_id and sp.is_del=0

left join parent p on p.parent_id=sp.parent_id and p.is_del=0 and p.org_id=s.org_id and p.org_id=suser.org_id

left join org_user puser on p.org_id=puser.org_id and p.user_id=puser.user_id and puser.org_id=suser.org_id and puser.org_id=s.org_id and puser.is_del=0 and puser.identity=0

where 1=1

and locate('132', puser.user_mobile)>0;

執行結果為:

從結果可以看出,表c(card)的type為all

檢視card表的索引

未發現s.stud_id = c.stud_id 中stud_id設為索引,將該列新增索引

重新執行該sql語句,檢視結果:2.688

檢視sql的執行計畫:

type由 all----->ref,查詢結果顯著的提公升

mysql多表聯合查詢

我在工作中天天研究zen cart的程式,那個叫人痛苦,最近比較痛苦的是經常碰見mysql多表聯合查詢,多的時候有12個表聯合查詢,zen cart的程式設計師不知道是懶還是技術好,乙個語句完成啦20幾個功能模組需要的資料,我修改就痛苦的很 我只會select from table where id...

mysql多表聯合查詢

mysql多表聯合查詢操作,3個表以上操作的sql語句 from語句是表選擇語句,需要選擇多個表的時候,用逗號 來分割所選的表。還可以用join語句來定義結合條件。表的別名 選擇的表可以取別名,在下面的例子中,from所選擇的表名後用空格來分割別名 例子1 將表foo取別名 t1,將表bar 取別名...

mysql多表聯合查詢

建立表a插入資料 create table a id int 11 primary key,name varchar 6 not null age int 4 notnull insert into a values 1 111 20 insert into a values 2 222 20 in...