简体   繁体   中英

SQL Compact Double Foreign Key Problem

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?

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.

Votes
qid - primary key - bigint
uid - primary key - int
votedate - datetime
vote - bit

Questions
qid - primary key - identity - bigint
uid - int
img - nchar
postdate - datetime
title - nchar

You can create an index on Question (uid, qid) but don't make that the PK.

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.

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.

在此处输入图片说明

create table UserProfile (
      UserID  integer identity primary key
    , Email   nvarchar(512)
);

create table Question (
      QuestionID integer identity primary key
    , OwnerID    integer 
    , PostDate   datetime
    , Title      nvarchar(1000)
);
alter table Question
    add constraint fk1_Question foreign key (OwnerID) references UserProfile (UserID); 


create table Vote (
      UserID      integer
    , QuestionID  integer
    , VoteDate    datetime
);
alter table Vote
    add constraint pk1_Vote primary key (UserID, QuestionID)
  , add constraint fk1_Vote foreign key (UserID)      references UserProfile (UserID);
  , add constraint fk2_Vote foreign key (QuestionID)  references Question (QuestionID);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM