Why single primary key is better than composite keys?

前端 未结 9 1105
栀梦
栀梦 2020-12-05 10:34

Why is the rejection of composite keys in favor of all tables using a single primary key named id? Cause generally all ORM follow this.

EDIT

9条回答
  •  甜味超标
    2020-12-05 11:11

    Well, it's basically about keeping JOINs simple - which one is simpler to understand:

    SELECT
       p.ID, p.Name, p.City,
       c.ID, c.Country, c.ISOCode
    FROM
       dbo.Parent p
    INNER JOIN
       dbo.Child c on c.ParentID = p.ID
    

    or

    SELECT
       p.ID, p.Name, p.City,
       c.ID, c.Country, c.ISOCode
    FROM
       dbo.Parent p
    INNER JOIN
       dbo.Child c ON c.ParentName = p.Name
         AND c.ParentCity = p.City
         AND c.ParentCountry = p.Country
    

    If you have composite primary keys, anyone joining to your table from a child table must "drag along" all those columns, and all those columns are also going to be present in the child table and the JOIN statements are pretty messy. Much better to have a single (even surrogate) key for the JOIN!

提交回复
热议问题