假设我有下表:
TABLE: widget
- widget_id (not null, unique, auto-increment)
- model_name (PK)
- model_year (PK)
model_name
和 model_year
组成一个复合键。在另一个表中使用widget_id
作为FK有什么问题吗?
最佳答案
键是任意数量的列,可用于唯一标识表中的每一行。
在您显示的示例中,您的小部件表有两个键:
- 型号名称、型号年份
- widget_id
在标准 SQL 中,外键可以引用引用表上的任何声明的键(主键或唯一键)。我需要检查 MySQL 的合规性。
<小时/>摘自 MySQL 引用手册 foreign keys :
<小时/>InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
作为替代方案,如果您希望使用引用表中的复合键,则该表中将有两列对应于 model_name 和 model_year,然后将外键约束声明为:
ALTER TABLE OtherTable ADD CONSTRAINT
FK_OtherTable_Widgets (model_name,model_year)
references Widgets (model_name,model_Year).
<小时/>
关于 InnoDB 与 MyISAM,在 ALTER TABLE 的文档中
The FOREIGN KEY and REFERENCES clauses are supported by the InnoDB storage engine, which implements ADD [CONSTRAINT [symbol]] FOREIGN KEY (...) REFERENCES ... (...). See Section 13.6.4.4, “FOREIGN KEY Constraints”. For other storage engines, the clauses are parsed but ignored. The CHECK clause is parsed but ignored by all storage engines. See Section 12.1.17, “CREATE TABLE Syntax”. The reason for accepting but ignoring syntax clauses is for compatibility, to make it easier to port code from other SQL servers, and to run applications that create tables with references. See Section 1.8.5, “MySQL Differences from Standard SQL”.
关于mysql - 数据库设计: use a non-key as a FK?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510119/