sql - 一列外键到两列主键
可能的重复:
外键可以引用非唯一索引吗?
我刚刚将一个应用程序从 MySQL 移植到 PostgreSQL 和 MS SQL Server,我发现了奇怪的(至少据我所知)定义。
这是简化的示例。
为什么这在 MySQL 中是可能的?它应该如何表现?
create table t1 (a int, b int, primary key (a, b))
create table t2 (c int, a int references t1 (a))
t1.a 不是唯一的,甚至 t1.b 也不是唯一的。它们一起创建唯一的记录,这就是主键。 t2.a 是对 t1.a 的外键引用,但 t1.a 只是 t1 中主键的一部分。
您对此有何看法?
显然数据库设计是错误的?如果是这样,为什么 MySQL 允许这样做?
谢谢!
Possible Duplicate:
Can a foreign key reference a non-unique index?
I was just porting one application from MySQL to PostgreSQL and MS SQL Server and I found strange (at least to my knowledge) definition.
This is simplified example.
How come is this possible in MySQL and how should it behave?
create table t1 (a int, b int, primary key (a, b))
create table t2 (c int, a int references t1 (a))
t1.a is not unique, not even t1.b. Together they create unique record and that makes the primary key. t2.a is a foreign key reference to t1.a, but t1.a is just part of the primary key in t1.
What do you think about this?
Obviously the database design is wrong? If so, how come this is allowed in MySQL?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这取决于你的数据。我有一个一直使用的 SQL Server 数据库。对于大多数表,主键是实体 ID 和程序编号的组合。实体有多个程序。然而,我还有一个表,其中仅包含有关每个实体的信息,并且仅通过实体 ID 链接到其他表。
对于某些数据来说这是有效的关系。
I think it depends on your data. I have a SQL server database I use all the time. For most tables, the primary key is a combination of entity ID and program number. Entities have multiple programs. Yet I also have a table that just has information about each entity and only links to other tables through the entity ID.
It's a valid relationship for some data.