【问题标题】:Asc order mysql query taking time than Desc orderAsc 命令 mysql 查询比 Desc 命令花费时间
【发布时间】:2021-04-29 10:32:46
【问题描述】:

我有这样的查询:

select 
   p.id, 
   p.status as status, 
   p.promotionid as id, 
   p.name as name, 
   p.promotion_type     as promotionType, 
   p.created_date as createdDate, 
   p.start_date as startDate, 
   p.end_date as endDate,
   p.orders_display_count, 
   p.users_display_count, 
   pd.display_name as displayName
from promotion p 
inner join promotion_details pd on p.promotion_details=pd.id 
where p.tenant_id = '1234' 
  and p.status = 'active' 
order by users_display_count asc limit 0, 40;

上面的查询大约需要 3 秒,但是当我将 users_display_count 更改为 desc 顺序时,它需要 0.5 秒。两种排序顺序都使用相同的“users_display_count”列索引,知道为什么会这样,有什么方法可以改善 asc 顺序询问? 谢谢。

【问题讨论】:

  • Edit 显示完整的表架构,包括列类型和键。此外,检查并发布执行计划。

标签: mysql sorting join innodb sqlperformance


【解决方案1】:

limit 对您的执行时间的影响取决于您的数据内容。

您正在使用users_display_count 上的索引。这意味着 MySQL 将按该顺序遍历您的数据。

假设您有 40 个活动行,其中有 p.tenant_id = '1234'users_display_count = 1000,而所有其他租户都有一些值 users_display_count < 1000。在这种情况下,当您使用asc 时,请求的行位于索引的最后,因此 MySQL 必须在达到 40 行之前读取完整的索引。另一方面,如果您使用desc,则读取的前 40 行将适合,您就完成了。这种极端情况表明,ascdesc 的执行时间不同并不一定令人惊讶。

您的具体数据介于两者之间。这也意味着,对于asc,不同的租户可能会更快。

如何让ascdesc 一样快?

这在一定程度上取决于为什么这些行在读取asc 时不太可能符合条件。例如。可能是users_display_count 值较大的行更可能具有promotion_details(然后desc 更可能适合join 条件)。但是假设一个相对均匀的分布,很可能,添加一个适当的索引应该可以解决它。所以尝试添加索引promotion(tenant_id, users_display_count) 或者(如果很多行是非活动的)可能是promotion(tenant_id, status, users_display_count)。那么ascdesc 的执行时间可能会更相似(而且很可能比现在快得多)。

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2011-08-21
    • 2012-08-19
    • 2016-05-09
    • 2013-01-17
    相关资源
    最近更新 更多