2016-02-12 68 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有多个行(由于=),第一个将失败。

而第二种有更多的优化机会。第一个是基本扫描第一个表格并在第二个表格中查找值。

这些差异没有一个是“更好”或“更差”。它们根本不同,取决于您的需求。