Foreign key constraints and non-unique indexes in MySQL
While foreign keys are generally considered to establish a one-to-one relationship, in some cases this relationship is not strictly enforced. This behavior is common in certain scenarios, especially when using MySQL.
In MySQL, foreign key constraints can reference non-unique indexes in the referenced table. This means that a row in the referencing table can match multiple rows in the referenced table based on the index column.
This seeming deviation from the one-to-one principle does not weaken the purpose of foreign key constraints. It just allows for different interpretations of uniqueness. Rather than requiring an exact match, the database considers it sufficient that at least one record matches the foreign key value.
However, be sure to consider the impact of using foreign keys on non-unique columns. The "ON DELETE CASCADE" behavior becomes less clear in this case because there may be more than one matching record that needs to be deleted.
To avoid potential confusion and unwanted effects, it is strongly recommended to quote UNIQUE (including PRIMARY) and NOT NULL keys when defining foreign key constraints. This ensures unambiguous behavior and avoids ambiguities in data relationships.
The above is the detailed content of Can Foreign Keys Reference Non-Unique Indexes in MySQL?. For more information, please follow other related articles on the PHP Chinese website!