值是主键还是外键?

时间:2017-09-26 10:27:25

标签: sql sql-server

我的SQL Server数据库中有以下表格。

客户是用户的子类型,因此我从客户到用户进行了参考。

我还想将我的客户与我的预订联系起来。我想在Customer表中使用Foreign键作为此关系的PK。当我在SQL Server中写出这个时,我在"(userid)"下得到了这个错误:

  

无效的列'用户ID'

我该如何建立这种关系?

Create table [dbo].[User]
(
    [id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
    [name] varchar(50) NOT NULL,
    [password] nvarchar(100) NOT NULL, 
)

Create table [dbo].[Customer]
(
    [userid] int FOREIGN KEY REFERENCES [dbo].[User](id) NOT NULL,
    [street] varchar(40) NOT NULL,
    [housenumber] varchar(10) NOT NULL,
    [postalcode] varchar(10) NOT NULL,
    [phonenumber] varchar(20) NOT NULL,
    [email] varchar(30) NOT NULL,
)

Create table [dbo].[Reservation]
(
    [id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
    [datum] date NOT NULL,
    [prijs] decimal NOT NULL,
    [levertijd] datetime NOT NULL,
    [ophaaltijd] datetime NOT NULL,
    [leverAdres] varchar(60) NOT NULL,
    [klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](userid) NOT NULL
)

1 个答案:

答案 0 :(得分:1)

是的,这是可能的,试试这个

Create table [dbo].[Customer]
(
  [userid] int not null,
  [street] varchar(40) NOT NULL,
  [housenumber] varchar(10) NOT NULL,
  [postalcode] varchar(10) NOT NULL,
  [phonenumber] varchar(20) NOT NULL,
  [email] varchar(30) NOT NULL,

  constraint PK_UserID primary key ([userid]),
  constraint FK_Customer_User foreign key (userid) references [User] (id)
)

但我必须说userid似乎是一个名为Customer的表的奇怪主键

我会这样:

Create table [dbo].[Customer]
(
  [CustomerID] int not null identity,
  [userid] int not null,
  [street] varchar(40) NOT NULL,
  [housenumber] varchar(10) NOT NULL,
  [postalcode] varchar(10) NOT NULL,
  [phonenumber] varchar(20) NOT NULL,
  [email] varchar(30) NOT NULL,

  constraint PK_CustomerID primary key ([CustomerID]),
  constraint FK_Customer_User foreign key (userid) references [User] (id)
)


Create table [dbo].[Reservation]
(
  [id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
  [datum] date NOT NULL,
  [prijs] decimal NOT NULL,
  [levertijd] datetime NOT NULL,
  [ophaaltijd] datetime NOT NULL,
  [leverAdres] varchar(60) NOT NULL,
  [klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](customerid) NOT NULL