|This article does not cite any references (sources). (December 2009)|
In database management systems following the relational model, a junction table is a database table that contains common fields from two or more other database tables within the same database. It is the standard way of creating a many-to-many relationship between tables.
In most database systems, only one-to-one or one-to-many relationships between data tables can be created directly, usually by utilizing foreign keys. The Foreign Key (FK) usually is a Primary Key (PK) of another table and thus a unique constraint.
A junction table maps two or more tables together by referencing the primary keys of each data table. In effect, it contains a number of foreign keys, each in a many-to-one relationship from the junction table to the individual data tables. The primary key of the junction table is typically composed of the FK columns themselves, but may employ its own PK as well.
Junction tables are known under many names, including mapping table, cross-reference table, bridge table, join table, intermediary table, intersection table, intersection entity, linking table, many-to-many resolver, link table, pairing table, transition table, crosswalk, associative entity or association table.
Using junction tables
A practical use of a junction table would be to assign permissions to users. There can be multiple users, and each user can be assigned 0 or more permissions. Individual permissions may be granted to more than one user.
CREATE TABLE Users ( UserLogin varchar(50) PRIMARY KEY, UserPassword varchar(50) NOT NULL, UserName varchar(50) NOT NULL ) CREATE TABLE Permissions ( PermissionKey varchar(50) PRIMARY KEY, PermissionDescription varchar(500) NOT NULL ) -- This is the junction table. CREATE TABLE UserPermissions ( UserLogin varchar(50) REFERENCES Users (UserLogin), PermissionKey varchar(50) REFERENCES Permissions (PermissionKey), PRIMARY KEY (UserLogin, PermissionKey) )
SELECT * FROM Users JOIN UserPermissions USING (UserLogin);
This will return a list of all users and their permissions.
Inserting into a junction table involves multiple steps: first inserting into the main table(s), then updating the junction table.
-- Creating a new User INSERT INTO Users (UserLogin, UserPassword, UserName) VALUES ('SomeUser', 'SecretPassword', 'UserName'); -- Creating a new Permission INSERT INTO Permissions (PermissionKey, PermissionDescription) VALUES ('TheKey', 'A key used for several permissions'); -- Finally, updating the junction INSERT INTO UserPermissions (UserLogin, PermissionKey) VALUES ('SomeUser', 'TheKey');
Using foreign keys, the database will automatically dereference the values of the UserPermissions table to their own tables.
|This computer science article is a stub. You can help Wikipedia by expanding it.|