【问题标题】:MySql and subselect, why is it so slow?MySql和subselect,为什么这么慢?
【发布时间】:2012-08-10 18:16:42
【问题描述】:

我在这里有这个选择:

select parent_id from sales_flat_order_status_history where status like '%whatever%' group by parent_id having count(parent_id) > 1

这个查询只运行几秒钟。现在我想在另一个选择中使用它,像这样:

select increment_id from sales_flat_order where entity_id in(
select parent_id from sales_flat_order_status_history where status like '%whatever%' group by parent_id having count(parent_id) > 1)

这会永远运行,所以我尝试一一插入 id:

select increment_id from sales_flat_order where entity_id in(329,523,756,761,763,984,1126,1400,1472,2593,3175,3594,3937,...)

这运行得很快,区别在哪里,我怎样才能让我的第一种方法运行得更快?

谢谢!

【问题讨论】:

    标签: mysql query-optimization subquery


    【解决方案1】:

    您的查询需要很长时间才能运行,因为它正在执行子查询并查找 sales_flat_order 表的每一行。

    加入可能会更快:

    select increment_id 
    from sales_flat_order
      inner join (select parent_id 
                  from sales_flat_order_status_history 
                  where status like '%whatever%' 
                  group by parent_id having count(parent_id) > 1) Sub 
      on sales_flat_order.entity_id  = Sub.parent_ID
    

    这会强制子查询只执行一次

    【讨论】:

    • 是的,确实快得多!谢谢
    【解决方案2】:

    子查询以 foreach 样式处理(对每一行进行子选择)。

    in (1,2,3) 这样的想法不要对一些旧版本的mysql 使用索引。

    【讨论】:

    • 所以我不能让它更快?
    猜你喜欢
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2012-11-13
    • 2011-03-07
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多