SQL紧凑双外键问题
以下是数据库的基本版本:
问题
uid - 主键 - int
qid - 主键 - 身份 - bigint
img - nchar
postdate - 日期时间
标题 - nchar
用户配置文件
电子邮件 - nchar
UserId - 主键 - 身份 - int
投票
qid - 主键 - bigint
uid - 主键 - int
votedate - 日期时间
vote - bit
我遇到的问题是我希望投票的 uid 成为 UserTable 中的外键,投票的 qid 成为问题中的外键(显然是 qid)。当我尝试添加与 WebMatrix 的关系时,我不断收到错误“引用的表必须具有主键或候选键”。我做错了什么?
Below is a basic version of the database:
Questions
uid - primary key - int
qid - primary key - identity - bigint
img - nchar
postdate - datetime
title - nchar
UserProfile
Email - nchar
UserId - primary key - idendity - int
Votes
qid - primary key - bigint
uid - primary key - int
votedate - datetime
vote - bit
the problem I am having is I want uid of Votes to be the foreign key from UserTable and qid of Votes being foreign key from Questions (qid obviously). When I try to add relationships with WebMatrix I keep getting the error "The referenced table must have a primary or candidate key." What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
外键必须引用另一个表中的唯一键。从你的问题来看,不清楚你是否打算将item1或item2作为PK,或者(item1, item2)的组合是否是唯一的。如果是组合,那么这是来自另一个表的外键的唯一有效链接。
问题的 PK 由两列组成,因此要创建从投票到问题的 FK,您需要 2 列来连接它。然而,最好只用一列创建一个简单的 PK。然后,你的 FK 就可以工作了。
您可以在问题(uid,qid)上创建索引,但不要将其作为主键。
A foreign key MUST reference a unique key from another table. From your question it is not clear whether you intend for item1 or item2 to be the PK, or whether the combination of (item1, item2) is unique. If it is the combination, then that is the only valid link for a foreign key from another table.
The PK of Questions is made of two columns, so to create a FK from Vote to Question, you need 2 columns to join to it. It would be better however to create a simple PK with just one column. Then, your FK will work.
You can create an index on Question (uid, qid) but don't make that the PK.
不熟悉 WebMatrix,所以我不知道它是否特别有复合键的问题。
不过,我确实注意到,问题中的主键是 (uid, qid),这与投票中的 qid(本身)作为问题的外键不兼容。
Not familiar with WebMatrix, so I don't know if it, in particular, has problem with composite keys.
I do note, however, that the primary key in Questions is (uid, qid) and that is not compatible with having qid in Votes (by itself) be a foreign key to Questions.
我也遇到了同样的问题,无意中找到了解决方案。
您需要确保主键索引表的字段顺序与关系中的字段顺序相同。
I had the same problem and accidently found a solution.
You need to ensure that the primary key index table has the same order of fields as in the relation.