I need to introduce a many-to-many relationship between two tables, which both have an integer for primary key, in a SQL Server database. How is this best done in T-SQL?
Consider the following two example table definitions for which there should be a many-to-many relationship:
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)
);
The traditional way is to use an additional
many:many(junction) table, which links to both tables:One moot point is whether you want the compound key
AuthorId, BookIdto be the Primary Key, or whether to add your own new Surrogate – this is usually a subjective preference.Some of the points to consider whether going for a compound primary key or a new surrogate key for the Junction table:
AuthorIdandBookIdas foreign keys).BooksorAuthorstables without first joining to the junction table.The following diagram hopefully makes the case of the compound key clearer (the middle table
Nationalityis a junction table ofPersonCountry):Edit
Usage is straightforward – if the link exists in the many:many table, then the relationship is deemed to exist. To test the existence, you ‘join through’ the link table e.g.