ADD COLUMN

ALTER TABLE.. ADD COLUMN 语句用于在已有表中添加列。在 TiDB 中,ADD COLUMN 为在线操作,不会阻塞表中的数据读写。

语法图

AlterTableStmt:

AlterTableStmt

AlterTableSpec:

AlterTableSpec

ColumnKeywordOpt:

ColumnKeywordOpt

ColumnDef:

ColumnDef

ColumnPosition:

ColumnPosition

示例

  1. mysql> CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY auto_increment);
  2. Query OK, 0 rows affected (0.11 sec)
  3. mysql> INSERT INTO t1 VALUES (NULL);
  4. Query OK, 1 row affected (0.02 sec)
  5. mysql> SELECT * FROM t1;
  6. +----+
  7. | id |
  8. +----+
  9. | 1 |
  10. +----+
  11. 1 row in set (0.00 sec)
  12. mysql> ALTER TABLE t1 ADD COLUMN c1 INT NOT NULL;
  13. Query OK, 0 rows affected (0.28 sec)
  14. mysql> SELECT * FROM t1;
  15. +----+----+
  16. | id | c1 |
  17. +----+----+
  18. | 1 | 0 |
  19. +----+----+
  20. 1 row in set (0.00 sec)
  21. mysql> ALTER TABLE t1 ADD c2 INT NOT NULL AFTER c1;
  22. Query OK, 0 rows affected (0.28 sec)
  23. mysql> SELECT * FROM t1;
  24. +----+----+----+
  25. | id | c1 | c2 |
  26. +----+----+----+
  27. | 1 | 0 | 0 |
  28. +----+----+----+
  29. 1 row in set (0.00 sec)

MySQL 兼容性

  • 不支持同时添加多列。
  • 不支持将新添加的列设为 PRIMARY KEY
  • 不支持将新添加的列设为 AUTO_INCREMENT

另请参阅