我创建了两个表。我需要在Friends
的第二个表中有两个ID。 UserId
是UserInformation
表中的ID。该表中已经有FriendId
个ID。我需要在这两个表之间建立关系,并正确制作FK和PK。我尝试自己做,但它却在尖叫我没有在这里做的事情-参考[UserInformation](UserId)
我需要您的帮助才能正确完成工作
CREATE TABLE [dbo].[UserInformation]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[Login] [VARCHAR](50) NOT NULL,
[Password] [VARCHAR](50) NOT NULL,
[FirstName] [NCHAR](10) NOT NULL,
[LastName] [NCHAR](10) NOT NULL,
[Email] [VARCHAR](50) NOT NULL,
[RegistrationDate] [DATETIME] NOT NULL,
[Groups] [VARCHAR](50) NOT NULL
)
GO
CREATE TABLE [dbo].[Friends]
(
[UserId] [INT] NOT NULL,
[FriendId] [INT] NOT NULL,
PRIMARY KEY (FriendId),
CONSTRAINT FK_UserInformationFriend
FOREIGN KEY (UserId) REFERENCES [UserInformation](UserId)
)
GO
ALTER TABLE [dbo].[UserInformation]
ADD CONSTRAINT [DF_UserInformation_RegistrationDate]
DEFAULT (GETDATE()) FOR [RegistrationDate]
GO
ALTER TABLE UserInformation
ADD CONSTRAINT DF_UserInformation_Login_Unique UNIQUE(Login)
GO
ALTER TABLE UserInformation
ADD CONSTRAINT DF_UserInformation_Email_Unique UNIQUE(Email)
GO
ALTER TABLE UserInformation
ADD CONSTRAINT [PK_UserInformation] PRIMARY KEY ([Id])
GO
ALTER TABLE Friends
ADD CONSTRAINT [PK_Friends] PRIMARY KEY ([UserId])
GO
答案 0 :(得分:1)
首先将其更改为:
CREATE TABLE [dbo].[UserInformation](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Login] [varchar](50) NOT NULL,
[Password] [varchar](50) NOT NULL,
[FirstName] [nchar](10) NOT NULL,
[LastName] [nchar](10) NOT NULL,
[Email] [varchar](50) NOT NULL,
[RegistrationDate] [datetime] NOT NULL,
[Groups] [varchar](50) NOT NULL
)
然后:
CREATE TABLE [dbo].[Friends](
[UserId] [int] NOT NULL,
[FriendId] [int] NOT NULL,
PRIMARY KEY (FriendId),
CONSTRAINT FK_UserInformationFriend FOREIGN KEY (UserId)
REFERENCES [UserInformation](Id)
)
最后一个:
ALTER TABLE [dbo].[UserInformation]
ADD CONSTRAINT [DF_UserInformation_RegistrationDate] DEFAULT
(getdate()) FOR [RegistrationDate]
GO
ALTER TABLE UserInformation
ADD CONSTRAINT DF_UserInformation_Login_Unique UNIQUE (Login)
GO
ALTER TABLE UserInformation
ADD CONSTRAINT DF_UserInformation_Email_Unique UNIQUE (Email)
这两个表都不需要设置它们作为主表:
ALTER TABLE UserInformation
ADD CONSTRAINT [PK_UserInformation] PRIMARY KEY ([Id])
GO
ALTER TABLE Friends
ADD CONSTRAINT [PK_Friends] PRIMARY KEY ([UserId])
GO
注意:如果您需要多个主键,请使用复合主键:
primary key (FriendId, UserId)