首页 > 解决方案 > 使用临时文件和文件排序总是不好的吗?

问题描述

我有一种情况,我在 where 子句中最多指定 100 个主键。

一个示例查询:

select  product_id, max(date_created) AS last_order_date
    from  orders
    where  product_id=28906
      or  product_id=28903
      or  product_id=28897
      or  product_id=28848
      or  product_id=28841
      or  product_id=28839
      or  product_id=28838
      or  product_id=28837
      or  product_id=28833
      or  product_id=28832
      or  product_id=28831
      or  product_id=28821
      or  product_id=28819
      or  product_id=28816
      or  product_id=28814
      or  product_id=28813
      or  product_id=28802
      or  product_id=28800
      or  product_id=28775
      or  product_id=28773
    group by  product_id
    order by  date_created desc

解释节目Using index condition; Using temporary; Using filesort

我知道我应该避免使用 查询Using temporary; Using filesort,但是即使对于大型数据集,查询执行时间也很快,我是否必须避免它?我已经给出了一个 ID 列表,所以这个查询是我能做的最好的。

如果我决定继续使用查询,我应该期待什么副作用或缺点?

解释输出:

1   SIMPLE  wc_order_product_lookup range   product_id  product_id  8   NULL    3   Using index condition; Using temporary; Using filesort

标签: mysqlsqloptimization

解决方案


文件排序用于group byorder by。这很难避免。in但是,您可能会发现对where子句有帮助:

select product_id,  max(date_created)  AS last_order_date
from orders
where product_id in (28906, 28903, 28897, . . . )
group by product_id
order by date_created desc;

推荐阅读