[英]MySQL queries performance comparison
在這兩個查詢之間,一個查詢比MySQL 5.7.19中的另一個查詢快嗎?
select {some columns}
from
table1 t1
join table2 t2 using ({some columns})
where t1.col1=1
與
select {some columns}
from
(select {some columns} from table1 where col1=1) t1
join table2 t2 using ({some columns})
假設所有索引均已正確設置
我創建了一個SQL Fiddle,以便我們可以進行實驗。
您的第一個查詢翻譯為:
select *
from
table1 t1
join table2 t2 on t2.table1_id = t1.id
where t1.col1=1
執行計划是:
id select_type表的類型
1 SIMPLE t1 ref id,col1 col1 4 const 2 100.00使用索引
1 SIMPLE t2 ref table1_id table1_id 4 db_9_0005cd.t1.id 1 100.00使用索引
這幾乎是可能的最快速度。
您的第二個查詢變為
select *
from
(select * from table1 where col1=1) as t1
join table2 t2 on t2.table1_id = t1.id
執行計划是:
id select_type表的類型
1主t2索引table1_id table1_id 4 3 100.00使用索引
1個主要參考4 db_9_0005cd.t2.table1_id 2100.00
2派生表1引用col1 col1 4 const 2 100.00使用索引
此處的區別在於您正在使用派生表,但仍在使用索引。 我的期望是,只要數據庫不受資源限制,這將與版本1一樣快地執行-如果您遇到內存或CPU限制,第二個查詢的行為可能會更加不可預測。
然而...
理論上的方法不能替代使用具有測試數據的測試環境,並在具有代表性的條件下進行調整。 我懷疑您正在構建的實際查詢是否會像示例一樣簡單...
對於那些簡單的查詢,涉及“派生表”(子查詢)的查詢肯定不會更快。
在其他情況下,派生表可以更快。 這包括GROUP BY
或LIMIT
在執行JOIN
之前減少行數的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.