Mysql查询效果不佳

时间:2012-06-05 15:01:46

标签: mysql sql optimization

我不是sql的专家,我需要以下查询的帮助。它的选择很差,执行时间太长。 是否可以将IN()替换为JOIN()以加快查询速度? 怎么做?

SELECT * 
FROM   shop_orders 
WHERE  id IN (SELECT orders_id 
              FROM   shop_orders_data 
              WHERE  closed = '1' /*AND backorder='0'*/) 
       AND id IN (SELECT orders_id 
                  FROM   shop_orders_products 
                  WHERE  products_id IN (SELECT id 
                                         FROM   shop_products 
                                         WHERE  artno = '120000' 
                                                 OR name LIKE '%120000%')) 
ORDER  BY created DESC 

4 个答案:

答案 0 :(得分:3)

我会说LIKE在这里造成了最大的延迟......艺术还不够吗? LIKE通常是一个非常昂贵的程序。

答案 1 :(得分:2)

我认为应该这样做:

SELECT 
  s.* 
FROM 
  shop_orders s 
INNER JOIN
  shop_orders_data od 
ON 
  s.id=od.orders_id 
INNER JOIN
  shop_orders_products sop 
ON 
  s.id=sop.orders_id 
INNER JOIN 
  shop_products sp 
ON 
  sop.products_id=sp.id 
WHERE
  od.closed=1
AND 
  ( sp.artno='120000' or sp.name LIKE '%120000%' )

答案 2 :(得分:1)

是的,你走在正确的道路上 - 你可以在所有这些表之间建立一个内连接而不是这些IN运算符。

SELECT
    so.* 
FROM 
    shop_orders so
    INNER JOIN shop_orders_data sod
       ON so.id = sod.orders_id
    INNER JOIN shop_orders_products sop
       ON sod.id = sop.orders_id
    INNER JOIN shop_products sp
       ON sop.products_id = sp.id
WHERE sod.closed = '1'
    AND (sp.artno = '120000' OR sp.name LIKE '%120000%')

答案 3 :(得分:1)

Select so.*
from shop_orders as so
     join shop_orders_data as sod on sod.orders_id = so.id
     join (select orders_id 
           from   shop_orders_products as sop
                  join shop_products as sp on sp.id = sop.products_id
           where  sp.artno = '120000' 
                  OR sp.name like '%120000%') as sop on sop.orders_id = so.id
where 
  sod.closed = '1'
order by so.created desc