Only one key from composite primary key as foreign key

倾然丶 夕夏残阳落幕 提交于 2019-12-06 14:35:29

问题


In this database, key1 & key2 make up the composite primary key of table4, but i'm able to add a foreign key to table3 that comprise just key1.

Why MySQL allows this? Does the above database design make no sense at all?


回答1:


TL;DR It's not standard SQL. MySQL documentation itself advises not doing it.

In SQL a FOREIGN KEY declaration must reference a column list declared PRIMARY KEY or UNIQUE NOT NULL. (PRIMARY KEY creates a UNIQUE NOT NULL constraint.) (The constraint has to be explicit, even though any set of NOT NULL columns containing a set that is UNIQUE has to be unique.)

The MySQL documentation says:

The handling of foreign key references to non-unique keys or keys that contain NULL values is not well defined for operations such as UPDATE or DELETE CASCADE. You are advised to use foreign keys that reference only keys that are both UNIQUE (or PRIMARY) and NOT NULL.

(You can ponder just what are and are not the well-defined operations, since the documentation doesn't actually clarify.)

1.8.2.3 Foreign Key Differences
13.1.18 CREATE TABLE Syntax
13.1.18.6 Using FOREIGN KEY Constraints

In the relational model a FK references a CK (candidate key). A superkey is a unique column set. A CK is a superkey containing no smaller superkey. One CK can be called the PK (primary key). When a column set's values must appear elsewhere we say there is an IND (inclusion dependency). A FK is an IND to a CK. When an IND is to a superkey we could call that a "foreign superkey".

SQL PRIMARY KEY declares a superkey. It is a PK (hence CK) when it does not contain a smaller UNIQUE NOT NULL column set. SQL UNIQUE NOT NULL declares a superkey. It is a CK when it does not contain a smaller PRIMARY KEY or UNIQUE NOT NULL column set. SQL FOREIGN KEY declares a foreign superkey. A PRIMARY KEY might actually be a PK (hence CK) and a UNIQUE NOT NULL might actually be a CK. Then an SQL FOREIGN KEY to these actually is a FK.




回答2:


Foreign keys are not dependent of primary keys at all. In fact, they have nothing to do with primary keys.

A primary keys single purpose is to identify a row uniquely.

A foreign keys purpose is to make sure that for each entry in the referencing table (the child table) there must be an entry in the referenced table (the parent table). It's only a technical requirement in MySQL that there must be an index (not necessarily a primary key or a unique key, a simple index suffices) on the referenced column.

Therefore your design makes sense, yes.



来源:https://stackoverflow.com/questions/44838200/only-one-key-from-composite-primary-key-as-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!