2016-02-12 41 views
0

在單一行,子選擇或連接上連接兩個表的更快方式應該是什麼?針對一行上的鏈接兩個表優化查詢

例如:

(1)子選擇

select * from main_territorypricing where item_id = 
(select id from main_iteminstance where platform_id = '8d6kgwzl6dcm') 

# explain 
id select_type table type possible_keys key key_len ref rows Extra 
1 PRIMARY main_territorypricing ref item_id item_id 5 const 1 Using where 
2 SUBQUERY main_iteminstance ref platform_id_index platform_id_index 182 const 1 Using where; Using index 

(2)加入

select p.* from main_territorypricing p 
inner join main_iteminstance i on p.item_id=i.id 
where i.platform_id='8d6kgwzl6dcm' 

# explain 
id select_type table type possible_keys key key_len ref rows Extra 
1 SIMPLE i ref PRIMARY,platform_id_index platform_id_index 182  const 1 Using where; Using index 
1 SIMPLE p ref item_id item_id 5 avails.i.id 1 NULL 

一個爲什麼會比其他優選的?注意所有連接的字段都被編入索引。

+0

可能的重複[加入與子查詢](http://stackoverflow.com/questions/2577174/join-vs-sub-query) – drneel

+0

@drneel我認爲這是一個普遍問題的重要參考,我認爲上述問題可能對單行加入查找的超特定情況有用。 – David542

回答

1

兩者不同。

當匹配時,第一個返回main_territorypricing中的一行。第二個打開存在多個匹配行的可能性。

同樣,如果main_iteminstance有多個行(由於=),第一個將失敗。

而第二種有更多的優化機會。第一個是基本掃描第一個表格並在第二個表格中查找值。

這些差異沒有一個是「更好」或「更差」。它們根本不同,取決於您的需求。