没有唯一约束匹配给定具有多个主键的引用表的键

时间:2015-08-20 03:44:38

标签: sql postgresql database-design foreign-keys

我正在尝试链接这两个表但收到错误:

  

没有唯一约束匹配引用表“mergelices”的给定键。

注意Robberies是另一张表 我用它来创建Accomplices表(这是发生错误时):

CREATE TABLE info.Accomplices (
RobberID    INTEGER,
BankName    VARCHAR,
City        VARCHAR,
RobberyDate DATE,
Share       DECIMAL NOT NULL,
PRIMARY KEY(RobberID, BankName, City, RobberyDate),
FOREIGN KEY(BankName, City, RobberyDate)
   REFERENCES info.Robberies(BankName, City, RobberyDate)
);

这就是创建强盗表:

CREATE TABLE info.Robbers (
RobberID    INTEGER,
Nickname    VARCHAR,
Age     INTEGER,
NoYears INTEGER,
PRIMARY KEY(RobberID),
FOREIGN KEY(RobberID) REFERENCES info.Accomplices(RobberID),
CONSTRAINT AgeCheck CHECK (Age > NoYears)
);

Robbers表中的外键是否需要匹配构成Accomplices表中主键的所有组件?

2 个答案:

答案 0 :(得分:2)

  

Robbers表中的外键是否需要匹配构成Accomplices表中主键的所有组件?

不完全是。它不一定是PK。 FK约束要求对引用表中的(一组)列的任何 UNIQUEPRIMARY KEY约束。如果它不是唯一的,则FK不能引用它。从理论上讲,您可以向UNIQUE添加accomplices约束:

CREATE TABLE info.Accomplices (
   robberid    integer,
   bankname    varchar,
   city        varchar,
   robberydate date,
   share       decimal not null,
   PRIMARY KEY(robberid, bankname, city, robberydate),
   UNIQUE(robberid),
   FOREIGN KEY ...
);

..从设计的角度来看,它的意义非常小,但在robbers中显示给定FK约束的要求。

我怀疑您的数据库设计存在逻辑问题。

相关:

答案 1 :(得分:1)

CREATE TABLE info.Robberies ( 
BankName    VARCHAR, 
City     VARCHAR, 
RobberyDate DATE, 
Amount  DECIMAL NOT NULL, 
PRIMARY KEY(BankName, City, RobberyDate), 
FOREIGN KEY(BankName, City) REFERENCES info.Banks(BankName, City) 
);

 CREATE TABLE info.Robbers (
 RobberID    INTEGER,
 Nickname    VARCHAR,
 Age     INTEGER,
 NoYears INTEGER,
 PRIMARY KEY(RobberID),
 --FOREIGN KEY(RobberID) REFERENCES info.Accomplices(RobberID),
 CONSTRAINT AgeCheck CHECK (Age > NoYears)
  );

 CREATE TABLE info.Accomplices (
 RobberID    INTEGER,
 BankName    VARCHAR,
 City        VARCHAR,
 RobberyDate DATE,
 Share       DECIMAL NOT NULL,
 PRIMARY KEY(RobberID, BankName, City, RobberyDate),
 FOREIGN KEY(RobberID) references info.Robbers(RobberID),
 FOREIGN KEY(BankName, City, RobberyDate) REFERENCES             
 info.Robberies(BankName, City, RobberyDate)
 );