我该如何优化这个mysql查询?我使用OR运算符

时间:2017-06-21 09:22:51

标签: mysql query-optimization

我得到了一个像这样的mysql查询:

select a.goods_id, 
       a.site_id,
       b.goods_name,
       a.cost,
       a.stock 
from rs_goods as a 
inner join rs_goods_multi as b 
   on a.goods_id = b.goods_id 
where a.goods_sn LIKE 'sweater005%' 
OR    b.goods_name LIKE 'sweater005%';

它显示类型'ALL',也许'OR'导致它,我怎样才能优化它,我为字段'goods_sn'和'goods_name'添加了索引。您可以在下面看到mysql捕获。mysql capture

1 个答案:

答案 0 :(得分:0)

使用UNION从查询中删除OR,通常可以获得更好的结果,因为每个查询都可以有效地使用单个索引。

select a.goods_id, 
       a.site_id,
       b.goods_name,
       a.cost,
       a.stock 
from rs_goods as a 
inner join rs_goods_multi as b 
   on a.goods_id = b.goods_id 
where a.goods_sn LIKE 'sweater005%' 
UNION
select a.goods_id, 
       a.site_id,
       b.goods_name,
       a.cost,
       a.stock 
from rs_goods as a 
inner join rs_goods_multi as b 
   on a.goods_id = b.goods_id 
where b.goods_name LIKE 'sweater005%'

看看这是否会带来更好的结果。