Relationship between tables n to n

Asked

Viewed 80 times

0

I’m creating a small project and I’m having a question.

Let’s assume that I have a certain types of coffees, these coffees can be served in more than two cup sizes. As the relationship between the tables are n to n, we have the following tables:

The SQL commands stay:

create table cafes (id_cafe int auto_increment not null, nome_cafe varchar(30) not null,
primary key (id_cafe));

create table xicara (id_xicara int auto_increment not null, nome_xicara varchar(30) not null,
primary key (id_xicara));

create table xicara_cafe (id_cafe int, id_xicara int,
primary key (id_cafe, id_xicara));

alter table xicara_cafe foreign key (id_cafe) references cafes(id_cafe);

alter table xicara_cafe foreign key (id_xicara) references xicara(id_xicara);

It turns out that is giving error exactly in the relationship between the tables. I wanted the tip for this impasse.

  • 2

    alter table ... ADD foreign key

1 answer

1

Formalizing the answer (cited in Havenard’s commentary), the ADD before the command foreign key:

alter table xicara_cafe add foreign key (id_cafe) references cafes(id_cafe);

alter table xicara_cafe add foreign key (id_xicara) references xicara(id_xicara);

You can still do it directly by creating the table:

create table xicara_cafe (id_cafe int, id_xicara int,
primary key (id_cafe, id_xicara),
foreign key(id_cafe) references cafes(id_cafe),
foreign key(id_xicara) references xicara(id_xicara));

Documentation of SQL FOREIGN KEY (in English).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.