好的,您正在寻找的是一个一对多的表格,但扭曲的是您可以参考原始表格,以获取黑名单用户的详细信息。因此,您的用户表看起来像这样,其中 AppUserID 是唯一标识用户的 PK。
CREATE TABLE [dbo].[AppUser](
[AppUserID] [bigint] IDENTITY(1,1) NOT NULL, -- Pk for the user
[UserName] [nvarchar](50) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[EmailAddress] [nvarchar](255) NULL,
CONSTRAINT [PK_APP_USER] PRIMARY KEY CLUSTERED ( [AppUserID] ASC)
)
GO
您的黑名单表将有 0,1,n.. 特定 AppUserId 的黑名单用户。您需要 AppUserBlacklistID 来唯一引用当前用户的特定黑名单用户。如果您需要删除或更新它们。所以你会使用 AppUserBlackListId
CREATE TABLE [dbo].[AppUserBlackList](
[AppUserBlackListID] [bigint] IDENTITY(1,1) NOT NULL,
[AppUserID] [bigint] NOT NULL, -- Foreign Key to the AppUser table to identify the users black listed 'Users'
[BlackListedAppUserID] [bigint] NOT NULL, -- Foreign Key to the AppUser table to identify the user that is black listed
[Reason] [nvarchar](255) NOT NULL,
CONSTRAINT [PK_APP_ROLE] PRIMARY KEY CLUSTERED (AppUserBlackListID ASC)
) ON [PRIMARY]
现在创建一些外键约束
-- Foreign key to the users table. This is used to list all the black listed users for a particular user
ALTER TABLE [dbo].[AppUserBlackList] WITH CHECK ADD CONSTRAINT [FK_AppUserBlackList.AppUserID_AppUser] FOREIGN KEY([AppUserID])
REFERENCES [dbo].[AppUser] ([AppUserID])
-- This is a Foreign Key to the App user for the user that is black listed. It should also be unique in that one user can only blacklist another
-- User one time.
ALTER TABLE [dbo].[AppUserBlackList] WITH CHECK
ADD CONSTRAINT [FK_AppUserBlackList.BlackListedAppUserID_AppUser] FOREIGN KEY([BlackListedAppUserID])
REFERENCES [dbo].[AppUser] ([AppUserID])
现在要真正严格设计,您可以设置一个独特的约束,以表明用户不能多次将某人列入黑名单,并且他们不能将自己列入黑名单。
要获取特定用户的所有黑名单用户..您加入 2 个表
Select AppUserBlackListID, AppUserID,BlackListedUserName
from
AppUser auCurrentUser
Inner join AppUserBlackList auBl
on auCurrentUser.AppUserId = auBl.AppuserID
Inner join AppUser auBlackListedUserDetails
on auBL.BlackListedAppUserID =auBlackListedUserDetails.AppUserID
Where au.AppUserId = 10
所以你需要加入回用户表以获取列入黑名单的用户详细信息
希望这可以帮助