以下是mysql代码的格式
select a,b,c
from table1
left join table2 on x=y
left join table3 on m=n
limit 100000, 10
当我有一个大的偏移量时,我知道如何优化极限。但是我无法找到优化多个表的解决方案,有什么方法可以使我的查询更快吗?
发布于 2021-06-04 10:24:02
首先,除非在查询中包含ORDER BY
子句,否则补偿和限制是不可预测的。如果没有ORDER BY
,则允许您的server按它选择的任何顺序返回结果行。
其次,大偏移量和小限制是一个臭名昭著的查询-性能反模式。你没什么办法解决这个问题。
为了获得良好的性能,可以重新考虑为什么要使用这种访问模式,然后尝试对某些索引列值使用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
是主键或唯一索引,这将是快速的。
https://stackoverflow.com/questions/67833698
复制相似问题