有没有办法避免查询子查询有三个子查询

时间:2011-06-08 19:56:13

标签: mysql

我有这个查询,它对性能很有用(不确定)

SELECT ssp.product_id, p.price
FROM system_step_product AS ssp
JOIN product AS p ON p.product_id=ssp.product_id 
WHERE ssp.system_id = 14
AND ssp.step_number = (
  SELECT step_number
  FROM system_step_product
  WHERE system_id = '14'
  AND step_number > (
    SELECT step_number
    FROM system_step_product
    WHERE system_id = '14'
    AND product_id = '81'
    ORDER BY step_number ASC
    LIMIT 1
  )  
  ORDER BY step_number ASC
  LIMIT 1
)

如果我必须采用这种方法,我会,但我想知道是否有人能想出更好的方法来执行此查询

3 个答案:

答案 0 :(得分:1)

这两个限制子句使得join语句需要row_number() OVER ()窗口函数,这在MySQL中是不可用的。即使这样,也可能使您的查询效率低于目前的效率。

答案 1 :(得分:0)

这是未经测试的,但也许你可以从中构建。

select 
        ssp.product_id, 
        p.price 
    from 
        system_step_product as ssp 
    join 
        product as p 
        on p.product_id = ssp.product_id        
    left join
        ( select min(step_number) as min_step_number
          from system_step_product
          where system_id = '14'
            and product_id = '81'
        ) minstep
        on minstep.min_step_number = ssp.step_number
    where
        minstep.min_step_number is null and
        ssp.system_id = 14 

答案 2 :(得分:0)

没有查看逻辑,你可以摆脱订单/限制1的东西:

    SELECT ssp.product_id, p.price
    FROM system_step_product AS ssp
    JOIN product AS p ON p.product_id=ssp.product_id 
    WHERE ssp.system_id = 14
    AND ssp.step_number = (
        SELECT MIN(step_number)
        FROM system_step_product
        WHERE system_id = '14'
        AND step_number > (
            SELECT MIN(step_number)
            FROM system_step_product
            WHERE system_id = '14'
            AND product_id = '81'
        )
    )

可能有更好的方法来完成你正在做的事情并抛弃内部查询,但很难说不了解查询的目标。

加上...定义'更好':)