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

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


http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

ALTER TABLE tablename MODIFY columnname INTEGER;

这将改变给定列的数据类型

根据您希望修改的列的数量,最好是生成一个脚本,或者使用某种mysql客户端GUI


你使用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)

alter table table_name modify column_name int(5)

你也可以用这个:

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

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

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 TABLE `tableName` MODIFY COLUMN `ColumnName` datatype(length);

Ex :

Alter TABLE `tbl_users` MODIFY COLUMN `dup` VARCHAR(120);

要改变列数据类型有变化 方法及修改方法

ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);

ALTER TABLE student_info MODIFY roll_no VARCHAR(255);

要更改字段名称,也可以使用change方法

ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);

https://dev.mysql.com/doc/refman/8.0/en/alter-table.html

您还可以为列设置默认值,只需在值后面添加default关键字。

ALTER TABLE [table_name] MODIFY [column_name] [NEW DATA TYPE] DEFAULT [VALUE];

这也适用于MariaDB(测试版本10.2)


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

ALTER TABLE [table_name] MODIFY [column_name] [new data type] 
DEFAULT [VALUE] COMMENT '[column comment]'