我一直在检查ALTER TABLE的MySQL文档,它似乎没有包含添加或修改列注释的方法。 我怎么能这么做呢?
-- for table
ALTER TABLE myTable COMMENT 'Hello World'
-- for columns
-- ???
尝试:
ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'
您可以使用修改列
来执行此操作。 只要做。。。
ALTER TABLE YourTable
MODIFY COLUMN your_column
your_previous_column_definition COMMENT "Your new comment"
替代:
yourtable
和表的名称your_column
和您的注释名称your_previous_column_definition
使用列的column_definition,我建议通过show CREATE TABLE yourtable
命令获取该列的column_definition,然后逐字复制以避免任何陷阱。*您的新注释
和您想要的列注释。例如。。。
mysql> CREATE TABLE `Example` (
-> `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
-> `some_col` varchar(255) DEFAULT NULL,
-> PRIMARY KEY (`id`)
-> );
Query OK, 0 rows affected (0.18 sec)
mysql> ALTER TABLE Example
-> MODIFY COLUMN `id`
-> int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!';
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE Example;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Example | CREATE TABLE `Example` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Look, I''m a comment!',
`some_col` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
*每当您在alter table
语句中使用modify
或change
子句时,我建议您从show CREATE table
语句的输出中复制列定义。 这可以防止您意外地丢失列定义的重要部分,因为您没有意识到需要将其包含在modify
或change
子句中。 例如,如果您modify
一个auto_increment
列,则需要在modify
子句中再次显式指定auto_increment
修饰符,否则该列将不再是auto_increment
列。 类似地,如果列被定义为NOT NULL
或具有default
值,则在对列执行modify
或change
时需要包括这些详细信息,否则将丢失。
SELECT
table_name,
column_name,
CONCAT('ALTER TABLE `',
table_name,
'` CHANGE `',
column_name,
'` `',
column_name,
'` ',
column_type,
' ',
IF(is_nullable = 'YES', '' , 'NOT NULL '),
IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default = 'CURRENT_TIMESTAMP', column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
extra,
' COMMENT \'',
column_comment,
'\' ;') as script
FROM
information_schema.columns
WHERE
table_schema = 'my_database_name'
ORDER BY table_name , column_name
注意:如果您愿意,可以只改进到一个表
@Rufinus给出的解决方案很棒,但是如果你有自动增量,它会破坏它。