加入多个表时如何优化限制偏移量?

时间:2021-06-04 08:09:30

标签: mysql query-optimization

这里是mysql代码的格式

select a,b,c 
from table1 
left join table2 on x=y 
left join table3 on m=n
limit 100000, 10

我知道当我有一个大的偏移量时优化限制。但是我找不到优化多表的解决方案,有什么办法可以让我的查询更快?

1 个答案:

答案 0 :(得分:0)

首先,除非在查询中包含 ORDER BY 子句,否则偏移量和限制是不可预测的。如果没有 ORDER BY,您的 SQL 服务器可以按它选择的任何顺序返回结果行。

第二,大偏移量和小限制是臭名昭著的查询性能反模式。您无能为力使问题消失。

为了获得不错的性能,重新思考为什么要使用这种访​​问模式,然后尝试对某些索引列值使用 WHERE 过滤器会很有帮助。

例如,假设您正在做这种事情。

select a.user_id, b.user_email, c.user_account
from table1 a
left join table2 b on a.user_id = b.user_id 
left join table3 c on b.account_id = c.account_id
limit whatever

假设您正在对查询进行分页,以便一次获得 50 个用户。然后您可以从程序中的 last_seen_user_id 变量开始,初始化为 -1

您的查询如下所示:

select a.user_id, b.user_email, c.user_account
from (
        select user_id 
          from table1 
         where user_id > ?last_seen_user_id?
         order by user_id
         limit 50
     ) u
join      table1 a on u.user_id = a.user_id
left join table2 b on a.user_id = b.user_id 
left join table3 c on b.account_id = c.account_id
order by a.user_id

然后,当您检索该结果时,将您的 last_seen_user_id 设置为结果中最后一行的值。

再次运行查询以获取接下来的 50 个用户。如果 table1.user_id 是主键或唯一索引,这会很快。

相关问题