我需要在SQL Server数据库中引入两个表之间的多对多关系,这两个表都有一个主键的整数。如何在T-SQL中做得最好?
考虑以下两个应该存在多对多关系的示例表定义:
CREATE TABLE [dbo].[Authors] (
[Id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_Versions] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Books] (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
答案 0 :(得分:3)
传统方法是使用附加many:many
表,该表链接到两个表:
CREATE TABLE [dbo].[AuthorsBooks] (
-- Can have your own surrogate if you want
[Id] INT IDENTITY(1,1) NOT NULL,
AuthorId INT NOT NULL,
BookId INT NOT NULL,
-- Referential Integrity
FOREIGN KEY(AuthorId) REFERENCES Authors(Id),
FOREIGN KEY(BookId) REFERENCES Books(Id),
-- PK can be own surrogate, or the composite (AuthorId, BookId)
PRIMARY KEY CLUSTERED ([Id] ASC)
);
一个问题是你是否希望复合键AuthorId, BookId
成为主键,或者是否要添加自己的新代理 - 这通常是主观偏好。
修改
用法很简单 - 如果链接存在于many:many表中,则认为该关系存在。要测试存在,您可以通过“链接表”加入,例如
-- Find all books written by AuthorId 1234
SELECT b.*
FROM Books b
INNER JOIN AuthorsBooks ab
ON b.Id = ab.BookId
WHERE ab.AuthorId = 1234