Foreign key vs check constraint for integrity

后端 未结 2 2057
死守一世寂寞
死守一世寂寞 2020-12-09 18:50

I am building a system that is a central repository for storing data from a number of other systems. A sync process is required to update the central repository when the oth

2条回答
  •  [愿得一人]
    2020-12-09 19:56

    The commentators seems to umanimously agree:

    It's generally better to have a FOREIGN KEY constraint to a (more or less static) reference table. Reasons:

    • The constraint is easily "extendable". To add or remove an option, you only have to add or remove a row from the refernce table. You don't have to drop the constraint and recreate it. Even more, if you have same constraint in similar columns in other tables, too.

    • You can have extra information attached (more columns), that can be read by the applications if needed.

    • ORMs can deal better with (Read: be aware of) these constraints. They just have to read a table, not the meta-data.

    • If you want to change the Action codes, the cascading effects will take care of the changes in other (possibly many) tables. No need to write UPDATE queries.

    • One particular DBMS has not yet implemented CHECK constraints (shame), although it does have FK ones.

    As @pst mentioned (and I prefer this approach very much), you can use a sensible code instead of a surrogate integer ID. So, your table could be:

    Table: System

    SystemID Description
     1        Slave System 1
     2        Slave System 2
    

    Table: Action

    ActionCode Description
     I          Insert
     U          Update
     D          Delete
    

    Table: SyncAction

    ID  ActionCode  SystemID
     1     I          1
     2     U          1
    

提交回复
热议问题