只能通過ALTER TABLE不能create index
ALTER TABLE tbl_name ADD PRIMARY KEY (column), ALGORITHM=INPLACE, LOCK=NONE;
參數說明:
ALGORITHM=INPLACE
更優秀的解決方案,在當前表加索引,步驟:
1.創建索引(二級索引)數據字典
2.加共享表鎖,禁止DML,允許查詢
3.讀取聚簇索引,構造新的索引項,排序並插
入新索引
4.等待打開當前表的所有隻讀事務提交
5.創建索引結束
ALGORITHM=COPY
通過臨時表創建索引,需要多一倍存儲,還有更多的IO,步驟:
1.新建帶索引(主鍵索引)的臨時表
2.鎖原表,禁止DML,允許查詢
3.將原表數據拷貝到臨時表
4.禁止讀寫,進行rename,升級字典鎖
5.完成創建索引操作
LOCK=DEFAULT:默認方式,MySQL自行判斷使用哪種LOCK模式,儘量不鎖表
LOCK=NONE:無鎖:允許Online DDL期間進行併發讀寫操作。如果Online DDL操
作不支持對錶的繼續寫入,則DDL操作失敗,對錶修改無效
LOCK=SHARED:共享鎖:Online DDL操作期間堵塞寫入,不影響讀取
LOCK=EXCLUSIVE:排它鎖:Online DDL操作期間不允許對鎖表進行任何操作
給1E數據庫在線加索引
數據庫在線加索引
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 7995759
Server version: 5.7.25-log Source distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]> use sdorica_exp
MySQL [sdorica_exp]> show index from gashapon_outcome_records;
Empty set (0.00 sec)
MySQL [sdorica_exp]> select count(1) from gashapon_outcome_records;
+-----------+
| count(1) |
+-----------+
| 111579926 |
+-----------+
1 row in set (1 min 10.13 sec)
MySQL [sdorica_exp]> ALTER TABLE gashapon_outcome_records ADD INDEX idx_roll_gashapon_record_id (roll_gashapon_record_id) , ALGORITHM=INPLACE, LOCK=NONE;
Query OK, 0 rows affected (15 min 34.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
MySQL [sdorica_exp]> show index from gashapon_outcome_records;
+--------------------------+------------+-----------------------------+--------------+-------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------------------+------------+-----------------------------+--------------+-------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| gashapon_outcome_records | 1 | idx_roll_gashapon_record_id | 1 | roll_gashapon_record_id | A | 51825872 | NULL | NULL | YES | BTREE | | |
+--------------------------+------------+-----------------------------+--------------+-------------------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.01 sec)
MySQL [sdorica_exp]>