0

我不是 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

4 回答 4

3

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

于 2012-06-05T15:08:23.600 回答
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%' )
于 2012-06-05T15:08:19.733 回答
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
于 2012-06-05T15:11:30.193 回答
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%')
于 2012-06-05T15:07:56.287 回答