What's the best practice for primary keys in tables?

前端 未结 21 2240
别那么骄傲
别那么骄傲 2020-11-22 14:02

When designing tables, I\'ve developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements

21条回答
  •  难免孤独
    2020-11-22 14:22

    Just an extra comment on something that is often overlooked. Sometimes not using a surrogate key has benefits in the child tables. Let's say we have a design that allows you to run multiple companies within the one database (maybe it's a hosted solution, or whatever).

    Let's say we have these tables and columns:

    Company:
      CompanyId   (primary key)
    
    CostCenter:
      CompanyId   (primary key, foreign key to Company)
      CostCentre  (primary key)
    
    CostElement
      CompanyId   (primary key, foreign key to Company)
      CostElement (primary key)
    
    Invoice:
      InvoiceId    (primary key)
      CompanyId    (primary key, in foreign key to CostCentre, in foreign key to CostElement)
      CostCentre   (in foreign key to CostCentre)
      CostElement  (in foreign key to CostElement)
    

    In case that last bit doesn't make sense, Invoice.CompanyId is part of two foreign keys, one to the CostCentre table and one to the CostElement table. The primary key is (InvoiceId, CompanyId).

    In this model, it's not possible to screw-up and reference a CostElement from one company and a CostCentre from another company. If a surrogate key was used on the CostElement and CostCentre tables, it would be.

    The fewer chances to screw up, the better.

提交回复
热议问题