关联实体
外观
关联实体是关系模型与实体关系模型理论中的术语。关系型数据库要求用一个基本关系(即一个基本表)实现多对多的数据关系。这种基本关系称为关联表(associative table);还有许多名字:bridge table, cross-reference table, crosswalk, intermediary table, intersection table, join table, junction table, link table, linking table, many-to-many resolver, map table, mapping table, pairing table, transition table。
关联表通常包含指向其他多个表的多个外键。从关联表到单张数据表是多对一关系。
例子
[编辑]下例是给用户授权。有多个用户、多种权限,每个用户可以有0或多个权限,每种权限可以授予0或多个用户:
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);
这将列出所有用户的所有权限。
Inserting到关联表涉及多步:首先向主表插入数据,再修改/插入关联表。
-- 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');
参见
[编辑]参考文献
[编辑]- Hoffer, Jeffrey A.; Prescott, Mary B.; McFadden, Fred R. Modern Database Management 7th. Prentice Hall. 2004. ISBN 978-0131453203.
- Codd, E. F. A Relational Model of Data for Large Shared Data Banks. Communications of the ACM (ACM). 1970, 13 (6): 377–387. doi:10.1145/362384.362685.