¿Cómo agregar una clave primaria a una tabla MySQL?


Esto es lo que intenté pero falla:

alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;

¿Alguien tiene una propina?

 75
Author: kittykittybangbang, 2011-02-27

8 answers

Después de agregar la columna, siempre puede agregar la clave primaria:

ALTER TABLE goods ADD PRIMARY KEY(id)

En cuanto a por qué su script no estaba funcionando, debe especificar PRIMARY KEY, no solo la palabra PRIMARY:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;
 170
Author: The Scrum Meister,
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
2011-02-27 11:29:13

Si su tabla es bastante grande, mejor no use la instrucción:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;

Debido a que hace una copia de todos los datos en una tabla temporal, altera la tabla y luego la copia de nuevo. Mejor hazlo manualmente. Cambiar el nombre de la tabla:

rename table goods to goods_old;

Crear nueva tabla con clave primaria y todos los índices necesarios:

create table goods (
    id  int(10) unsigned not null AUTO_INCREMENT
    ... other columns ...
    primary key (id)
);

Mueva todos los datos de la tabla antigua a la nueva, deshabilitando las claves e índices para acelerar la copia:

USE USE ESTO PARA MyISAM TABLAS:

SET UNIQUE_CHECKS=0;
    ALTER TABLE goods DISABLE KEYS;
        INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
    ALTER TABLE goods ENABLE KEYS;
SET UNIQUE_CHECKS=1;

O

-- UTILICE ESTO PARA InnoDB TABLAS:

SET AUTOCOMMIT = 0; SET UNIQUE_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
    INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old; 
SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; COMMIT; SET AUTOCOMMIT = 1;

Se necesitan 2 000 segundos para agregar PK a una tabla con ~200 millones de filas.

 9
Author: Denis Makarskiy,
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-11-21 09:21:43

Columna existente

Si desea agregar una restricción de clave primaria a una columna existente, toda la sintaxis listada anteriormente fallará.

Para agregar una restricción de clave primaria a una columna existente use el formulario:

ALTER TABLE `goods`
MODIFY COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
 7
Author: MER,
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-07-18 10:13:15

Este código funciona en mi base de datos mysql:

ALTER TABLE `goods`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
 1
Author: Michał Myszor,
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
2015-02-11 12:20:00
ALTER TABLE GOODS MODIFY ID INT(10) NOT NULL PRIMARY KEY;
 1
Author: Vimit Patel,
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-10-27 12:30:52

Prueba esto,

alter table goods add column `id` int(10) unsigned primary key auto_increment
 0
Author: phponwebsites,
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
2015-02-09 05:57:07

No estoy seguro de si esto le importa a alguien más, pero prefiero la tabla id a la primera columna de la base de datos. La sintaxis para eso es:

ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;

Que es solo una ligera mejora con respecto a la primera respuesta. Si quieres que esté en una posición diferente, entonces

ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;

HTH, - ft

 0
Author: ftrotter,
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-03-30 21:08:08

Elimine las comillas para que funcionen correctamente...

Alter table goods add column id int (10) unsigned primary KEY AUTO_INCREMENT;

 -1
Author: Raja Muthukutty,
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-11-03 06:30:00