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

后端 未结 3 721
萌比男神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条回答
  •  [愿得一人]
    2021-01-13 15:55

    Yes, you need to create a third table with mappings of ids, something with columns like:

     item_id     (Foreign Key)
     category_id (Foreign Key)
    

    edit: you can treat item_id and category_id as a primary key, they uniquely identify the record alone. In some applications I've found it useful to include an additional numeric identifier for the record itself, and you might optionally include one if you're so inclined

    Think of this table as a listing of all the mappings between Items and Categories. It's concise, and it's easy to query against.

    edit: removed (unnecessary) primary key.

提交回复
热议问题