Skip to content

缺少索引导致慢查询

快速摘要

你的查询在没有索引的列上过滤 —— 数据库执行全表扫描,在大表上很慢。

为什么发生

  • WHERE 子句在没有索引的列上过滤,导致顺序扫描

  • 连接列缺少索引,迫使对连接表进行嵌套循环扫描

  • 索引被删除或从未为频繁查询的列创建

最小示例

✗ 错误代码
await db.query('SELECT * FROM orders WHERE customer_id = $1', [customerId]);
// No index on customer_id — full table scan on millions of rows
✓ 修复代码
await db.query('CREATE INDEX idx_orders_customer ON orders(customer_id)');
await db.query('SELECT * FROM orders WHERE customer_id = $1', [customerId]);
// Now uses index scan — fast even on millions of rows

在过滤列上创建索引让数据库直接找到匹配行而非扫描整个表。

如何诊断

  • 对查询运行 EXPLAIN ANALYZE 并查找 Seq Scan 或高成本值

  • 用 SHOW INDEXES 或 information_schema 检查表索引

  • 比较有无索引时查询的执行时间

如何修复

  • 在频繁过滤的列上创建索引:CREATE INDEX idx_name ON table(column)

  • 为多列 WHERE 子句创建复合索引:CREATE INDEX ON table(col1, col2)

  • 为频繁查询中使用的连接列和 ORDER BY 列添加索引

如何预防

  • 在 WHERE、JOIN 和 ORDER BY 子句中频繁使用的列上创建索引

  • 监控慢查询日志并为显示顺序扫描的查询添加索引

相关资源

相关术语

相关课程

← 返回语言