交集表可以處理這些關係。
下面是一個例子。 (序列,附加鍵等省略) message_text僅作爲示例使用 - 如果郵件數據可能發生變化,則包含全文可能是一種責任。
CREATE TABLE MESSAGES
(MESSAGE_ID INTEGER NOT NULL PRIMARY KEY
,MESSAGE_TEXT VARCHAR2(4000));
CREATE TABLE KEYWORDS
(KEYWORD_ID INTEGER NOT NULL PRIMARY KEY
,KEYWORD VARCHAR2(100));
CREATE TABLE MESSAGES_KEYWORDS
(MESSAGE_ID NOT NULL REFERENCES MESSAGES
,KEYWORD_ID NOT NULL REFERENCES KEYWORDS);
INSERT INTO MESSAGES
VALUES
(1,'IN A HOLE IN THE GROUND THERE LIVED A HOBBIT.');
INSERT INTO MESSAGES
VALUES
(2,'IT WAS A HOBBIT-HOLE, AND THAT MEANS COMFORT');
INSERT INTO KEYWORDS VALUES (1,'HOBBIT');
INSERT INTO KEYWORDS VALUES (2,'GROUND');
INSERT INTO KEYWORDS VALUES (3,'COMFORT');
INSERT INTO MESSAGES_KEYWORDS VALUES (1,1);
INSERT INTO MESSAGES_KEYWORDS VALUES (1,2);
INSERT INTO MESSAGES_KEYWORDS VALUES (2,1);
INSERT INTO MESSAGES_KEYWORDS VALUES (2,3);
查詢的關係加入了三個表:
SELECT
MESSAGES.MESSAGE_TEXT
,KEYWORDS.KEYWORD
FROM MESSAGES
INNER JOIN MESSAGES_KEYWORDS
USING (MESSAGE_ID)
INNER JOIN KEYWORDS
USING (KEYWORD_ID)
WHERE KEYWORDS.KEYWORD = 'HOBBIT';
SELECT
MESSAGES.MESSAGE_ID
,COUNT('X') COUNT_KEYWORDS
FROM MESSAGES
INNER JOIN MESSAGES_KEYWORDS
ON (MESSAGES.MESSAGE_ID = MESSAGES_KEYWORDS.MESSAGE_ID)
AND MESSAGES.MESSAGE_ID = 1
INNER JOIN KEYWORDS
USING (KEYWORD_ID)
GROUP BY MESSAGES.MESSAGE_ID;