如何避免在 mysql 查询中使用大输出进行完整 table 扫描

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

我有非常大的 table(超过 1000 万行)并查询其中 returns 大量数据。我需要更快地达到 运行。因此,我尝试添加覆盖索引(包括来自 where 子句和 id 的值),但即使在索引提示使用索引之后,仍然存在完整的 table 扫描。然后我削减 select 中的值(只留下 id)并添加覆盖索引,但仍然有完整的 table 扫描。如何避免完全 table 扫描? 我尝试为所有列创建覆盖索引并进行全索引扫描,但该解决方案比全 table 扫描更长。 还有其他优化方法吗?我尝试了索引,尝试删除不存在的(更改为 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); 

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

但是您可能会尝试用 LEFT OUTER JOIN 替换 dependent subquery,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