正在查看旧版本。 查看 当前版本.

与当前比较 查看页面历史记录

版本 1 下一个 »

Mysql数据库慢查询优化

1. Mysql出现慢查询原因

1.1 核心原因只有两点:

  1. 没有走主键索引或者其他索引或者索引建立的不合理(索引不合理创建导致BTree索引树太深了,查询与全表扫描差不多)
  2. 数据表太大,一次性扫描数据量过多


2.优化方法

① 针对没有创建主键索引的或者索引创建不合理的,请删除索引,并重建索引,如果表没有主键的,也需要添加上主键索引

(1) 普通索引

CREATE TABLE users (
  id INT,
  name VARCHAR(50),
  age INT,
  INDEX idx_name (name)  -- 普通索引
);

ALTER TABLE users ADD INDEX idx_age (age);

(2) 唯一索引

CREATE TABLE users (
  id INT,
  email VARCHAR(100) UNIQUE,  -- 隐式唯一索引
  UNIQUE INDEX idx_email (email)  -- 显式唯一索引
);

ALTER TABLE users ADD UNIQUE INDEX idx_email (email);


(3) 主键索引

CREATE TABLE users (
  id INT PRIMARY KEY,  -- 主键索引(自动创建)
  name VARCHAR(50)
);

ALTER TABLE users ADD PRIMARY KEY (id);


(4) 全文索引

CREATE TABLE articles (
  id INT,
  content TEXT,
  FULLTEXT INDEX idx_content (content)  -- 全文索引(仅适用于 MyISAM/InnoDB)
);

ALTER TABLE articles ADD FULLTEXT INDEX idx_content (content);


(5) 空间索引

CREATE TABLE locations (
  id INT,
  point GEOMETRY NOT NULL,
  SPATIAL INDEX idx_point (point)  -- 空间索引(需使用 MyISAM 或支持空间索引的引擎)
);

ALTER TABLE locations ADD SPATIAL INDEX idx_point (point);


(6) 组合索引

CREATE TABLE orders (
  user_id INT,
  order_date DATE,
  INDEX idx_user_date (user_id, order_date)  -- 组合索引
);

ALTER TABLE orders ADD INDEX idx_user_date (user_id, order_date);



  • 无标签