MySQL-关系/中间表和JOIN查询?

问题描述 投票:0回答:1

阅读此书(已有很长时间了!),无法获得清晰的图像。

[首先,如果我有两个具有多对多关系的表(例如,配方和配料),并且创建了一个中间/关系表,如何编写一个SQL查询来查找所有配方,例如,香蕉他们?

第二,如果我可以在不创建第三张表的情况下使用JOIN查询找到相同的信息,那我为什么会有这个第三张关系表?

非常感谢您提供清晰,有用的解释,谢谢。

mysql join many-to-many relational
1个回答
0
投票

我如何编写SQL查询来查找其中包含香蕉的所有食谱?

您可以做:

select distinct r.id, r.name
from recipe r
join recipe_ingredient ri on ri.id_recipe = r.id
join ingredient i on i.id = ri.id_ingredient
where i.name = 'banana'

由于配方可以包含许多成分,并且成分可以与许多配方相关,所以这两个表之间的关系不是1:n而是n:m。因此,您需要一个中间表,如下所示:

create table recipe (
  id int primary key not null,
  name varchar(20)
);

create table ingredient (
  id int primary key not null,
  name varchar(20)
);

create table recipe_ingredient (
  id int primary key not null,
  id_recipe int not null,
  id_ingredient int not null,
  quantity double not null,
  foreign key fk1 (id_recipe) references recipe (id),
  foreign key fk2 (id_ingredient) references ingredient (id)
);
© www.soinside.com 2019 - 2024. All rights reserved.