Why do I need to use foreign key if I can use WHERE?

前端 未结 10 1419
难免孤独
难免孤独 2020-12-23 16:34

A beginners\' question about foreign key in MySQL.

In w3school it says,

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.<

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 17:09

    the RESTRICT operator (WHERE) has nothing to do with referential constraints!

    quote from C. J. Date's Relational Database Dictionary

    foreign key Let R1 and R2 be relvars, not necessarily distinct, and let K be a key for R1. Let FK be a subset of the heading of R2 such that there exists a possibly empty sequence of attribute renamings that maps K into K' (say), where K' and FK contain exactly the same attributes. Then FK is a foreign key

    referential integrity Loosely, the rule that no referencing tuple is allowed to exist if the corresponding referenced tuple doesn't exist. More precisely, let FK be some foreign key in some referencing relvar R2; let K be the corresponding key in the corresponding referenced relvar R1, and let K' be derived from K as described under foreign key. Then the referential integrity rule requires there never to be a time at which there exists an FK value in R2 that isn't the K' value for some (necessarily unique) tuple in R1 at the time in question. R1 and R2 here are the referenced relvar and the referencing relvar, respectively, and the constraint between them is a referential constraint.

    Examples: In relvar SP, {S#} and {P#} are foreign keys corresponding to the keys {S#} and {P#} in relvars S and P, respectively. Note that the key in the referenced relvar that corresponds to a given foreign key is not required to be a primary key specifically.

提交回复
热议问题