【问题标题】:MySQL - Relational/intermediary tables and JOIN queries?MySQL - 关系/中间表和 JOIN 查询?
【发布时间】:2020-05-06 00:39:44
【问题描述】:

一直在阅读此内容(很长时间了!),但无法获得清晰的图片。

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

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

非常感谢清晰、有用的解释,谢谢。

【问题讨论】:

    标签: mysql join many-to-many relational


    【解决方案1】:

    如何编写 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'
    

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

    由于一个食谱可以有 许多 成分,并且一个成分可以与 许多 食谱相关,因此这两个表之间的关系不是 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)
    );
    

    如果一种成分总是出现在一个配方中,那么结构会更简单,正如您所想的那样。这个更简单的结构可能看起来像:

    create table recipe (
      id int primary key not null,
      name varchar(20)
    );
    
    create table ingredient (
      id int primary key not null,
      name varchar(20),
      id_recipe int not null,
      foreign key fk3 (id_recipe) references recipe (id) 
    );
    

    在这种情况下,像这样的模型并不实​​用。您最终会多次使用相同的成分。例如,如果蛋糕使用“面粉”而面包使用“面粉”,那么“面粉”将在配料表中出现两次。不是个好主意。

    【讨论】:

    • 谢谢!从我阅读的许多文章中,我得到的印象是可以使用 JOIN 来查询 n:m 关系,而无需中间表。或者如果要查询 n:m 相关数据,您是否必须有一个中间表?
    • 感谢@the-impaler,将回复标记为答案。经过几周的编码,现在它更有意义了。但在我的评论问题中,您确实必须具有链接/中间表来查询 n:m 相关数据,对吗?谢谢
    • @Matthew 是的,数据库模型需要有中间第三张表来设计n:m关系。
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2013-02-27
    • 2011-07-26
    • 2011-09-01
    • 2013-05-10
    相关资源
    最近更新 更多