MySQL 3.23+ 引入,內部映射為 ALTER TABLE。不能創建主鍵索引,僅支援普通索引與唯一索引。
CREATE [UNIQUE] INDEX index_name
ON tbl_name (col_name [(length)] [ASC | DESC], ...)
[index_option ...]
index_name:可選,若省略自動生成(首列名)。(length):BLOB/TEXT/長 VARCHAR **必須指定前綴長度**。ASC/DESC:語法兼容,實際存儲均升序(MySQL 8.0+ 支援降序索引)。MySQL 3.22+ 引入,內部同為 ALTER TABLE。
DROP INDEX index_name ON tbl_name
-- 假設表 student(id, english, chinese, history)
CREATE INDEX idx_scores ON student (english, chinese, history);
-- 檢查索引結構
SHOW INDEX FROM student;
+---------+------------+----------+--------------+-------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name |
+---------+------------+----------+--------------+-------------+
| student | 1 | idx_scores | 1 | english |
| student | 1 | idx_scores | 2 | chinese |
| student | 1 | idx_scores | 3 | history |
+---------+------------+----------+--------------+-------------+
-- Seq_in_index 確認列順序:english → chinese → history
-- 刪除索引
DROP INDEX idx_scores ON student;
-- 添加普通索引
ALTER TABLE student ADD INDEX idx_scores (english, chinese, history);
-- 添加唯一索引
ALTER TABLE student ADD UNIQUE INDEX uk_scores (english, chinese, history);
-- 添加主鍵(CREATE INDEX 不支援)
ALTER TABLE student ADD PRIMARY KEY (id);
-- 刪除索引
ALTER TABLE student DROP INDEX idx_scores;
idx_表_列 / uk_表_列,避免自動生成的不可讀名稱。sys.schema_unused_indexes (5.7+ sys schema) 或 pt-index-usage 分析慢查詢日誌。CREATE INDEX/DROP INDEX 是 ALTER TABLE 的語法糖,**無法創建主鍵**,生產建議直接用 ALTER TABLE。掌握 SHOW INDEX 驗證 Seq_in_index 列順序,是聯合索引生效的關鍵檢查點。