我有非常大的表(超過 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);
uj5u.com熱心網友回復:
幾乎不可能告訴你任何事情,因為你沒有展示你的表是如何定義的,包括你正在使用的實際索引。
但是您可能會嘗試的一件事是用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;
- 在以下列上創建多列索引:Table1.id、Table1.userId、Table1.Added、Table1.Lost、Table1.NewId
- 如果以下列尚未編入索引,則在它們上創建索引:Table2.Id、Table2.userId、table2.Added、Table2.Del
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409824.html
標籤:
