Should every MySQL table have an auto-incremented primary key?

后端 未结 3 1897
半阙折子戏
半阙折子戏 2021-02-15 15:35
  • I understand the value of primary keys.
  • I understand the value of indexes.

Should every MySQL table have an auto-incremented prim

3条回答
  •  伪装坚强ぢ
    2021-02-15 16:22

    I am not a huge fan of surrogate keys. I have yet to see a scenario where I would prefer to use one for every table of a database.

    I would say No.

    Read up on this answer: surrogate-vs-natural-business-keys


    The above may be seen as sarcastic or flaming (despite the surprisingly many upvotes) so it's deleted.

    In the general case, there have been many questions and answers on surrogate and natural keys so I felt this question is more like a duplicate. My view is that surrogate keys are fine and very useful, mainly because natural keys can lead to very big primary keys in the low end of a chain of connected tables - and this is not handled well by many RDBMS, clustered indexes get big, etc. But saying that "every MySQL table should have an auto-incremented primary key" is a very absolute statement and I think there are cases when they really offer little or nothing.

    Since the OP updated the question, I'll try to comment on that specific topic.

    I think this is exactly a case where an autoincrementing primary key is not only useless but adds negative value. Supposing that table1 and table2 are in 1:1 relationship, the memberid can be both the Primary Key and a Foreign Key to table1.

    Adding an autoincrementing id column adds one index and if it's a clustered one (like InnoDB PK indexes) increases the size of the memberid index. Even more, if you have such an auto-incrementing id, some JOIN of table2 to other tables will have to be done using this id (the JOINs to tables in 1:n relation to table2) and some using memberid (the JOINs to tables in 1:n relation to table1). If you only have memberid both these types of JOINs can be done using memberid.

提交回复
热议问题