Why is a primary-foreign key relation required when we can join without it?

前端 未结 5 838
攒了一身酷
攒了一身酷 2020-12-02 08:31

If we can get data from two tables without having primary and foreign key relation, then why we need this rule? Can you please explain me clearly, with suitable example? It\

5条回答
  •  遥遥无期
    2020-12-02 09:08

    You don't need a FK, you can join arbitrary columns.

    But having a foreign key ensures that the join will actually succeed in finding something.

    Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.

    For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.

    Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)

提交回复
热议问题