If I have two tables in SQL with a many-many relationship, do I need to create an additional table?

后端 未结 3 734
萌比男神i
萌比男神i 2021-01-13 15:16

Take these tables for example.

Item
    id
    description
    category

Category
    id
    description 

An item can belong to many catego

3条回答
  •  萌比男神i
    2021-01-13 15:53

    Yes, you need a "join table". In a one-to-many relationship, objects on the "many" side can have an FK reference to objects on the "one" side, and this is sufficient to determine the entire relationship, since each of the "many" objects can only have a single "one" object.

    In a many-to-many relationship, this is no longer sufficient because you can't stuff multiple FK references in a single field. (Well, you could, but then you would lose atomicity of data and all of the nice things that come with a relational database).

    This is where a join table comes in - for every relationship between an Item and a Category, the relation is represented in the join table as a pair: Item.id x Category.id.

提交回复
热议问题