¿Cómo puedo cambiar el tipo de datos de una columna en MySQL?


Quiero cambiar el tipo de datos de varias columnas de float a int. ¿Cuál es la forma más sencilla de hacer esto?

Todavía no hay datos de los que preocuparse.

 356
Author: Eric Wilson, 2009-08-31

8 answers

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

ALTER TABLE tablename MODIFY columnname INTEGER;

Esto cambiará el tipo de datos de la columna dada

Dependiendo de la cantidad de columnas que desee modificar, podría ser mejor generar un script, o usar algún tipo de interfaz gráfica de usuario del cliente mysql

 701
Author: Yannick Motton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-31 10:53:57
alter table table_name modify column_name int(5)
 41
Author: php,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-24 18:42:01

También puedes usar esto:

ALTER TABLE [tablename] CHANGE [columnName] [columnName] DECIMAL (10,2)
 30
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-22 22:53:44

Si desea cambiar todas las columnas de un tipo determinado a otro tipo, puede generar consultas utilizando una consulta como esta:

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>';

Por ejemplo, si desea cambiar las columnas de tinyint(4) a bit(1), ejecútelo de la siguiente manera:

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)';

Y obtener una salida como esta:

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;

!! No mantiene restricciones únicas, pero se debe arreglar fácilmente con otro if-parámetro a concat. Dejaré que el lector lo implemente si es necesario..

 8
Author: Tobb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-17 15:32:58
Alter TABLE `tableName` MODIFY COLUMN `ColumnName` datatype(length);

Ex :

Alter TABLE `tbl_users` MODIFY COLUMN `dup` VARCHAR(120);
 6
Author: Mahrukh Mehmood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-20 05:36:58

Se utiliza el método alter table ... change ..., por ejemplo:

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)
 5
Author: Ólafur Waage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-09 23:20:14

Para cambiar el tipo de datos de columna hay change método y modificar método

alter table student_info change roll_no roll_no varchar(255);

alter table student_info modify roll_no varchar(255);

Para cambiar el nombre del campo también use el método change

alter table student_info change roll_no identity_no varchar(255);
 1
Author: Hasib Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 09:35:15

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

También puede establecer un valor predeterminado para la columna simplemente agregue la palabra clave PREDETERMINADA seguida del valor.

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

Esto también funciona para MariaDB (versión probada 10.2)

 1
Author: Michael01Angelo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-03 05:05:01