Optimizing query for Link two tables on one row

时间:2016-02-12 20:09:49

标签: mysql sql query-optimization

What should be the faster way to join two tables on a single row, the subselect or the join?

For example:

(1) Subselect

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) Join

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

Why would one be preferable over the other? Note all joined fields are indexed.

1 个答案:

答案 0 :(得分:1)

The two are different.

The first returns exactly one row in 255 when there is a match. The second opens the possibility of there being multiple matching rows.

Similarly, the first will fail if main_territorypricing has more than one row (because of the main_iteminstance).

And, the second has more opportunities for optimization. The first is basically scanning the first table and looking up the values in the second.

None of these differences are "better" or "worse". They are simply different, depending on your needs.