Are there any good reasons to have a database table without an integer primary key?

前端 未结 11 1814
感动是毒
感动是毒 2021-02-10 00:30

Although I\'m guilty of this crime, it seems to me there can\'t be any good reason for a table to not have an identity field primary key.

Pros: - whether you want to o

11条回答
  •  隐瞒了意图╮
    2021-02-10 00:52

    The most clear example of a table that doesn't need a surrogate key is a many-to-many relation:

    CREATE TABLE Authorship (
      author_id INT NOT NULL,
      book_id   INT NOT NULL,
      PRIMARY KEY (author_id, book_id),
      FOREIGN KEY (author_id) REFERENCES Authors (author_id),
      FOREIGN KEY (book_id) REFERENCES Books (book_id)
    );
    

    I also prefer a natural key when I design a tagging system:

    CREATE TABLE Tags (
      tag VARCHAR(20) PRIMARY KEY
    );
    
    CREATE TABLE ArticlesTagged (
      article_id INT NOT NULL,
      tag        VARCHAR(20) NOT NULL,
      PRIMARY KEY (article_id, tag),
      FOREIGN KEY (article_id) REFERENCES Articles (article_id),
      FOREIGN KEY (tag) REFERENCES Tags (tag)
    );
    

    This has some advantages over using a surrogate "tag_id" key:

    • You can ensure tags are unique, without adding a superfluous UNIQUE constraint.
    • You prevent two distinct tags from having the exact same spelling.
    • Dependent tables that reference the tag already have the tag text; they don't need to join to Tags to get the text.

提交回复
热议问题