MySQL-Hacer un par de valores únicos


Tengo una tabla con dos valores int que son IDs. Por su cuenta, estos ID pueden aparecer cualquier número de veces en la tabla, pero juntos solo deben aparecer una vez.

¿Hay alguna manera de hacer que un par de valores sea único y aún así permitir que los valores individuales se muestren varias veces?

Como seguimiento, si esto es posible, ¿se puede usar el par de valores como clave? Actualmente tengo una 3ra columna para un valor de incremento automático único para mi clave.

Author: Josh Brittain, 2012-10-07

3 answers

Se llama clave compuesta.

Si desea cambiar su PK real a uno compuesto, use

Alter table <your table> drop PRIMARY KEY;
Alter table <your table> drop COLUMN <your autoincremented column>;

Alter table <your table> add [constraint <constraint name>] PRIMARY KEY (<col1>, <col2>);

También puede agregar una restricción única (su PK será el mismo, y pares únicos... tendrá que ser único).

alter table <your table> add [constraint <constraint name>] unique index(<col1>, <col2>);

Personalmente, recomendaría la segunda solución (simple PK + restricción única), pero eso es solo un punto de vista personal. Puede buscar en Google argumentos de pros y contras sobre las claves compuestas.

La parte entre [] son opcional.

EDITAR

Si desea hacer esto en la instrucción create table

Para un compuesto pk

CREATE TABLE Test(
       id1 int NOT NULL, 
       id2 int NOT NULL,
       id3 int NOT NULL,
       PRIMARY KEY (id1, id2)
    );

Para un índice único

CREATE TABLE Test1(
       id1 int NOT NULL  AUTO_INCREMENT, 
       id2 int NOT NULL,
       id3 int NOT NULL,
       PRIMARY KEY (id1),
       UNIQUE KEY (id2, id3)
    );
 54
Author: Raphaël Althaus,
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-04-16 13:23:08

Prueba esto: ALTER TABLE table_name ADD CONSTRAINT uc_name UNIQUE (col1,col2)

 8
Author: Przemek Lewandowski,
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
2012-10-06 20:52:19

Agregue primary key (col1, col2) a su definición de crear tabla

 0
Author: jspcal,
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
2012-10-06 20:48:13