繁体   English   中英

如何避免在 mysql 查询中使用大 output 进行全表扫描

[英]How to avoid full table scan in mysql query with large output

我有非常大的表(超过 1000 万行)和返回大量数据的查询。 我需要让它跑得更快。 因此,我尝试添加覆盖索引(由 where 子句和 id 的值组成),但即使在对 USE INDEX 进行索引提示之后,仍然存在全表扫描。 然后我削减了 select 中的值(只剩下 id)并添加了覆盖索引,但仍然有全表扫描。 如何避免全表扫描? 我尝试为所有列创建覆盖索引并进行全索引扫描,但该解决方案比全表扫描更长。 还有其他优化方法吗? 我尝试了索引,尝试删除不存在(更改为 id not in),这一切都让时间变得更糟。 我有 Table1.id、table1.UserId、Table2.Id 的索引。

select t.id, t.Date, t.Added , t.NewId, t.UserId, t.Lost 
from Table1 t
where t.Added=0 and t.Lost=0 
   and not exists (select 1
                    from table2 n 
                    where n.Id=t.id and n.userId=t.userId and n.Added=0 and n.Del=0); 

几乎不可能告诉你任何事情,因为你没有展示你的表是如何定义的,包括你正在使用的实际索引。

但是您可能会尝试的一件事是用LEFT OUTER JOIN替换您的依赖子查询,MySQL 引擎可能能够更好地优化:

select t.id, t.Date, t.Added , t.NewId, t.UserId, t.Lost 
from Table1 t
left join table2 n on n.Id=t.id and n.userId=t.userId and n.Added=0 and n.Del=0
where t.Added=0 and t.Lost=0 and n.Id is null;
  1. 在以下列上创建多列索引:Table1.id、Table1.userId、Table1.Added、Table1.Lost、Table1.NewId
  2. 如果以下列尚未编入索引,则在它们上创建索引:Table2.Id、Table2.userId、table2.Added、Table2.Del

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM