Error creating Foreign Key in MySQL Workbench

0

I have a table called "maintenance_events" and another one called "maintenance_invitations". Both tables have a column called "date" of type "DATE" and NN.

When creating the Foreign Key between these columns I receive the following error:

table "maintenance_invitations":

table "maintenance_events":

It does not let me select any reference column and if I do, it gives me an error:

What could be the error, how can I fix this?

    
asked by Robert Gomez 28.11.2016 в 21:37
source

1 answer

2

In MySQL, foreign keys can only be applied by referring to a column that has an associated index, as explained in official documentation .

For example, let's review this script:

-- Creamos una tabla T1 (padre)
CREATE TABLE t1(
campo1 VARCHAR(10) NOT NULL,
fecha DATE NOT NULL);

-- Creamos una tabla T2 (hija)
CREATE TABLE t2(
campo2 VARCHAR(10) NOT NULL,
fecha DATE NOT NULL,
fechaT1 DATE NOT NULL -- intentaremos referenciar la fecha de T1
);

-- Intentamos crear una llave foránea en t2
-- sobre la columna fechaT1
-- que se asocie a la columna FECHA de la tabla T1.
-- Esto va a fallar.
ALTER TABLE t2
ADD FOREIGN KEY (fechaT1) REFERENCES t1(fecha);

-- Alteramos la tabla T1
-- para crear un índice sobre la columna FECHA
ALTER TABLE t1
ADD INDEX (fecha);

-- Ahora que existe un índice sobre T1.FECHA
-- intentaremos recrear la llave foránea en T2.
-- Esto va a funcionar
ALTER TABLE t2
ADD FOREIGN KEY (fechaT1) REFERENCES t1(fecha);

So, the solution seems to be that you should only create an index on the field you require.

EYE . The real solution IS NOT the one I indicated above. Technically, it will solve the problem, but it is a bad database design . What you should do is create true primary keys for both tables based on a numerical ID and associate the tables with their primary keys. In script, this would be:

-- el prefijo mantenimiento_ no aplica en aplicaciones del mundo real

CREATE TABLE evento (
    id INT PRIMARY KEY AUTO_INCREMENT,
    nombre VARCHAR(45) NOT NULL,
    fecha DATE NOT NULL,
    ubicacion VARCHAR(150) NOT NULL,
    tipo VARCHAR(20) NOT NULL
);

-- La columna "nombre" no tiene mucho sentido porque lo que necesitas
-- es el nombre del invitado.
-- "fecha" tampoco tiene sentido porque la fecha de la invitación
-- es en realidad la fecha del evento
-- a menos que tu intención sea indicar la fecha de entrega
-- de la invitación
-- de ser así, sería mejor colocar un nombre más apropiado
-- para esa columna
CREATE TABLE invitacion (
    id INT PRIMARY KEY AUTO_INCREMENT,
    invitado VARCHAR(45) NOT NULL,
    -- El id del evento como columna que nos permitirá
    -- crear la referencia mediante una llave foránea
    id_evento INT NOT NULL,
    -- La llave foránea que define la relación entre las tablas
    -- evento (padre) e invitacion (hija)
    FOREIGN KEY (id_evento) REFERENCES evento(id)
);
    
answered by 28.11.2016 / 22:05
source