關聯實體
關聯實體是關係模型與實體關係模型理論中的術語。關係型數據庫要求用一個基本關係(即一個基本表)實現多對多的數據關係。這種基本關係稱為關聯表(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.