我想把多个列的数据类型从float改为int。最简单的方法是什么?

目前还没有数据可以担心。


当前回答

alter table table_name modify column_name int(5)

其他回答

你也可以用这个:

ALTER TABLE [tablename] CHANGE [columnName] [columnName] DECIMAL (10,2)

如果要更改列详细信息、设置默认值并添加注释,请使用此选项

ALTER TABLE [table_name] MODIFY [column_name] [new data type] 
DEFAULT [VALUE] COMMENT '[column comment]' 
alter table table_name modify column_name int(5)

如果你想把某一类型的所有列都更改为另一种类型,你可以使用这样的查询生成查询:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' <new datatype> ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = '<your database>' 
    and column_type = '<old datatype>';

例如,如果你想将列从tinyint(4)改为bit(1),可以这样运行:

select distinct concat('alter table ',
                       table_name,
                       ' modify ',
                       column_name,
                       ' bit(1) ',
                       if(is_nullable = 'NO', ' NOT ', ''),
                       ' NULL;')
  from information_schema.columns
  where table_schema = 'MyDatabase' 
    and column_type = 'tinyint(4)';

并得到如下输出:

alter table table1 modify finished bit(1)  NOT  NULL;
alter table table2 modify canItBeTrue bit(1)  NOT  NULL;
alter table table3 modify canBeNull bit(1)  NULL;

!! 不保留唯一的约束,但应该很容易用另一个if参数来连接。如果需要的话,我将把它留给读者来实现。

你使用alter表…改变……方法,例如:

mysql> create table yar (id int);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into yar values(5);
Query OK, 1 row affected (0.01 sec)

mysql> alter table yar change id id varchar(255);
Query OK, 1 row affected (0.03 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> desc yar;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
1 row in set (0.00 sec)