mysql - 数据库设计: use a non-key as a FK?

标签 mysql data-modeling database-design

假设我有下表:

TABLE: widget
 - widget_id (not null, unique, auto-increment)
 - model_name (PK)
 - model_year (PK)

model_namemodel_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/

相关文章:

使用 unix_timestamp() 后 MySQL 时间戳数学行为不同

php - 带有房间的实时聊天项目的数据库架构

mysql - 数据库关系循环,如何打破呢?

database-design - 引用 PK 的外键是否需要 NOT NULL 约束?

mysql - MyBatis useGeneratedKeys 批量插入嵌套对象

MySQL , JOIN , 当总数 = 1

Mysql 在大表上性能缓慢

redis - Phi 系数用例的键值存储 (Redis)

java - 集合作为现实世界容器的隐喻

mysql - 最大表和设计模式