Database FK Constraints vs Programmatic FK Constraints

前端 未结 3 563
既然无缘
既然无缘 2021-01-24 19:00

Although I am targeting MySQL/PHP, for the sake of my questions, I\'d like to just apply this generally to any relational database that is being used in conjunction with a moder

3条回答
  •  暖寄归人
    2021-01-24 19:44

    Just how familiar you are with database design and the foreign key concept in general? FK is a column(s) in one table that identifies a row in another table. (I'm pretty sure you already know this.) So FK constraint is something that exists in DB, not in application. Managing FK constraints in application requires manual coding for the functionalities that are already available in DB. So why would you want to do all that manual labor? Also the DB/application interaction and development is much more difficult because of all that extra manual coding.

    Best practice IMHO is to use the tools for what they are created to do. DB takes care of the FKs referential integrity and application doesn't need to concern itself with DBs inner functionalities. However, if referential integrity is your main concern and you're for example using MySQL with MyISAM engine which doesn't support FK constraints then you have to some manual checking in application (or maybe with DB triggers which I am not familiar with). Just keep in mind that when you do all kind of checking in application you still have to access the DB and thus you use more resources than what really is needed if the DB could handle the referential integrity checks. (The easy solution of course would be start using InnoDB engine but I'll stop here before this answer gets too product oriented).

    So some the pros for letting the DB handle the FK constraint would be:

    1. You don't have to think about it.
    2. You don't have to manually code anything extra.
    3. Application uses less resources and contains less code and thus...
    4. ... maintaining and developing both the DB and the application is a lot easier (for example the application developers don't need to understand database oriented concepts and functionalities so deeply, let the DB experts do the FK etc. thinking...).

提交回复
热议问题