关联实体

关联实体关系模型实体关系模型理论中的术语。关系型数据库要求用一个基本关系(即一个基本表)实现多对多的数据关系。这种基本关系称为关联表(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语句通常使用joining把主表变为宽表:

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. 7th. Prentice Hall. 2004. ISBN 978-0131453203.
    • Codd, E. F. . Communications of the ACM (ACM). 1970, 13 (6): 377–387. doi:10.1145/362384.362685.
    This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.