1

我在一个新数据库中设置了几个表。我有一张Users桌子,一张Companies桌子,一张UserCompanies桌子(这样一个用户可以为许多不同的公司工作)和一张UserPay桌子。

CREATE TABLE tblUsers
(
[UserTableID] INT IDENTITY NOT NULL PRIMARY KEY,    
[UserEmail] VARCHAR(50) NOT NULL,
[UserFirstName] VARCHAR(20) NOT NULL,
[UserLastName] VARCHAR(20) NOT NULL,
[UserAddress1] VARCHAR(45) NULL,
[UserAddress2] VARCHAR(45) SPARSE NULL,
[UserCity] VARCHAR(45) NULL,
[UserState] VARCHAR(2) NULL,
[UserZipCode] VARCHAR(10) NULL,
[UserPhone] VARCHAR(13) NULL,
)

CREATE TABLE tblCompanies
(
[CompanyID] INT IDENTITY NOT NULL PRIMARY KEY,
[CompanyName] VARCHAR(45) NOT NULL,
[CompanyAddress1] VARCHAR(45) NULL,
[CompanyAddress2] VARCHAR(45) SPARSE NULL,
[CompanyCity] VARCHAR(45) NULL,
[CompanyState] VARCHAR(2) NULL,
[CompanyPhone] VARCHAR(13) NULL,
[CompanyPhoneExtension] VARCHAR(8) NULL,
[CompanyContactFirstName] VARCHAR(20) NOT NULL,
[CompanyContactLastName] VARCHAR(20) NOT NULL
)

CREATE TABLE tblUserCompanies
(
[UserTableID] INT NOT NULL,
[CompanyID] INT NOT NULL,
PRIMARY KEY (UserTableID, CompanyID),
FOREIGN KEY (UserTableID) REFERENCES tblUsers(UserTableID),
FOREIGN KEY (CompanyID) REFERENCES tblCompanies(CompanyID)  
)

CREATE TABLE tblUserPay
(
[UserPayID] INT IDENTITY NOT NULL PRIMARY KEY,
[UserID] INT NOT NULL REFERENCES tblUserCompanies(UserTableID),
[UserCompany] INT NOT NULL REFERENCES tblUserCompanies(CompanyID),
[NetPay] MONEY NOT NULL,
[PayDate] DATE NOT NULL
)

问题是我收到一个错误,指出..“引用表中没有与 .tblUserCompanies中的引用列列表匹配的主键或候选键tblUserPay

我不明白为什么我会出错。相同的数据类型,完整的外键,建立的主键。我唯一能想到的是它会抛出一个错误,因为我有一个外键链接到另一个外键。如果可以的话请帮忙!谢谢

4

2 回答 2

1

链接到复合键时,您需要一个包含两列的外键引用,例如:

CREATE TABLE tblUserPay
(
[DriverPayID] INT IDENTITY NOT NULL PRIMARY KEY,
[UserID] INT NOT NULL,
[UserCompany] INT NOT NULL,
[NetPay] MONEY NOT NULL,
[PayDate] DATE NOT NULL,
FOREIGN KEY (UserID, UserCompany) REFERENCES tblUserCompanies(UserTableID, CompanyID)
)
于 2013-05-04T16:54:10.243 回答
0

按照这个示例

CREATE TABLE dbo.Table1(
    Table1Col1 int NOT NULL
    ,Table1Col2 int NOT NULL
    ,CONSTRAINT PK_Table1 PRIMARY KEY CLUSTERED(
        Table1Col1
        ,Table1Col2)    
);

CREATE TABLE dbo.Table2(
    Table2Col1 int NOT NULL
        CONSTRAINT PK_Table2 PRIMARY KEY CLUSTERED 
    ,Table1Col1 int NOT NULL
    ,Table1Col2 int NOT NULL
    ,CONSTRAINT FK_Table2_Table1 FOREIGN KEY(
        Table1Col1
        ,Table1Col2)
        REFERENCES dbo.Table1(
        Table1Col1
        ,Table1Col2
    )
);
于 2013-05-04T16:54:08.780 回答