SQL: Do you need an auto-incremental primary key for Many-Many tables?

后端 未结 7 885
半阙折子戏
半阙折子戏 2020-12-06 00:48

Say you have a Many-Many table between Artists and Fans. When it comes to designing the table, do you design the table like such:

ArtistFans
    ArtistFanID         


        
7条回答
  •  有刺的猬
    2020-12-06 01:27

    Funny how all answers favor variant 2, so I have to dissent and argue for variant 1 ;)

    To answer the question in the title: no, you don't need it. But...

    Having an auto-incremental or identity column in every table simplifies your data model so that you know that each of your tables always has a single PK column.

    As a consequence, every relation (foreign key) from one table to another always consists of a single column for each table.

    Further, if you happen to write some application framework for forms, lists, reports, logging etc you only have to deal with tables with a single PK column, which simplifies the complexity of your framework.

    Also, an additional id PK column does not cost you very much in terms of disk space (except for billion-record-plus tables).

    Of course, I need to mention one downside: in a grandparent-parent-child relation, child will lose its grandparent information and require a JOIN to retrieve it.

提交回复
热议问题