MySQL中的表、字段的约束修改

时间:2021-12-03 13:38:07

ALTER [IGNORE] TABLE tbl_name
alter_specification [, alter_specification] …

alter_specification:
ADD [COLUMN] column_definition [FIRST | AFTER col_name ]
| ADD [COLUMN] (column_definition,…)
| ADD INDEX [index_name] [index_type] (index_col_name,…)
| ADD [CONSTRAINT [symbol]]
PRIMARY KEY [index_type] (index_col_name,…)
| ADD [CONSTRAINT [symbol]]
UNIQUE [index_name] [index_type] (index_col_name,…)
| ADD [FULLTEXT|SPATIAL] [index_name] (index_col_name,…)
| ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name,…)
[reference_definition]
| ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
| CHANGE [COLUMN] old_col_name column_definition
[FIRST|AFTER col_name]
| MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
| DROP [COLUMN] col_name
| DROP PRIMARY KEY
| DROP INDEX index_name
| DROP FOREIGN KEY fk_symbol
| DISABLE KEYS
| ENABLE KEYS
| RENAME [TO] new_tbl_name
| ORDER BY col_name
| CONVERT TO CHARACTER SET charset_name [COLLATE collation_name]
| [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name]
| DISCARD TABLESPACE
| IMPORT TABLESPACE
| table_options
| partition_options
| ADD PARTITION partition_definition
| DROP PARTITION partition_names
| COALESCE PARTITION number
| REORGANIZE PARTITION partition_names INTO (partition_definitions)
| ANALYZE PARTITION partition_names
| CHECK PARTITION partition_names
| OPTIMIZE PARTITION partition_names
| REBUILD PARTITION partition_names
| REPAIR PARTITION partition_names

1、主键约束
alter table 表名 add [constraint] primary key (列名);
drop primary key;
2、外键约束
alter table 表名 add [constraint] foreign key (列名) references 表2(列名)
drop foreign key 外键名字(通过show create table 表名 查询出外键名字)
当删除外键之后,会留下自动创建的索引,用语句 alter table 表名 drop index 索引名字; 删除索引;
3、唯一键约束
alter table 表名 add [constraint] unique key (列名)
用语句 alter table 表名 drop index 索引名字;删除唯一键约束。
4、设置默认约束
alter table 表名 alter 列名 {set default literal| drop default}

5、修改列名称,及其类型:
alter table 表名 change 旧列名 新列名 类型;
6、修改列定义:
alter table 表名 [column] 列名 类型;

7、修改表名:
alter table 表名 rename [to] 新表名;
8、有check约束,但不会强制check。

9、 show create table 表名;
show columns form 表名;
show indexes from 表名\G; //以网格的形式输出。

alter_specification:
ADD [COLUMN] column_definition [FIRST | AFTER col_name ]
| ADD [COLUMN] (column_definition,…)
| ADD [CONSTRAINT [symbol]]
PRIMARY KEY [index_type] (index_col_name,…)
| ADD [CONSTRAINT [symbol]]
UNIQUE [index_name] [index_type] (index_col_name,…)
| ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name,…)
[reference_definition]
| ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
| CHANGE [COLUMN] old_col_name column_definition
[FIRST|AFTER col_name]
| MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
| DROP [COLUMN] col_name
| DROP PRIMARY KEY
| DROP INDEX index_name
| DROP FOREIGN KEY fk_symbol
| RENAME [TO] new_tbl_name
| ORDER BY col_name

| CHECK PARTITION partition_names