Should you make a self-referencing table column a foreign key?

前端 未结 4 786
夕颜
夕颜 2020-12-09 15:23

For example to create a hierarchy of categories you use a column \'parent_id\', which points to another category in the same table.

Should this be a foreign key? Wha

4条回答
  •  离开以前
    2020-12-09 15:42

    Yes you should.

    Advantages (as for any foreign key):

    • Ensures that parent_id references a real row in the table
    • Prevents accidental deletion of a parent that has children, or ensures that the delete cascades to delete the children also
    • Provides information the optimizer can use

    I can't think of any real disadvantages.

提交回复
热议问题