0

我有非常大的表(超过 1000 万行)和返回大量数据的查询。我需要让它跑得更快。所以我尝试添加覆盖索引(由 where 子句和 id 的值组成),但即使在索引提示 USE INDEX 之后仍然存在全表扫描。然后我在选择中剪切值(仅留下 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); 
4

1 回答 1

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
于 2022-01-13T12:19:23.903 回答