我有以下Oracle数据库概念:
我需要找到那些 Account_Household_IDs ,其中有 Main_ID ,中没有匹配的关联 Account_Member_ID > Support_ID 或 VIP_ID 列。我已经搜索了示例和答案,但我想我用来定义问题的搜索词并不够好。
提前致谢
答案 0 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE Account_Household (
Account_Household_ID NUMBER PRIMARY KEY
);
INSERT INTO Account_Household
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 100;
CREATE TABLE Account_Member (
Account_Member_ID NUMBER PRIMARY KEY,
Account_Household_ID NUMBER,
FOREIGN KEY ( Account_Household_ID ) REFERENCES Account_Household ( Account_Household_ID )
);
INSERT INTO Account_Member
SELECT LEVEL, 2*LEVEL FROM DUAL CONNECT BY LEVEL <= 50;
CREATE TABLE Account_Role (
Main_ID NUMBER,
Support_ID NUMBER,
FOREIGN KEY ( Main_ID ) REFERENCES Account_Member ( Account_Member_ID ),
FOREIGN KEY ( Support_ID ) REFERENCES Account_Member ( Account_Member_ID )
);
INSERT INTO Account_Role
SELECT LEVEL, 2*LEVEL FROM DUAL CONNECT BY LEVEL <= 25;
CREATE TABLE VIP_User (
VIP_ID NUMBER,
FOREIGN KEY ( VIP_ID ) REFERENCES Account_Member ( Account_Member_ID )
);
INSERT INTO VIP_User
SELECT 3*LEVEL FROM DUAL CONNECT BY 3*LEVEL < 25;
查询1 :
要查找父表中FOREIGN KEY
而不是子表时的行,则有各种选项,包括使用MINUS
操作,使用相关子查询和NOT EXISTS
或使用LEFT OUTER JOIN
并过滤子表中的NULL
条目:
SELECT m.Account_Member_ID,
m.Account_Household_ID
FROM Account_Member m
INNER JOIN
Account_Household h
ON ( m.Account_Household_ID = h.Account_Household_ID )
LEFT OUTER JOIN
Account_Role r
ON ( m.Account_Member_ID = r.Main_ID
OR m.Account_Member_ID = r.Support_ID )
LEFT OUTER JOIN
VIP_User v
ON ( m.Account_Member_ID = v.VIP_ID )
WHERE v.VIP_ID IS NULL
AND r.Main_ID IS NULL
ORDER BY m.Account_Member_ID
<强> Results 强>:
| ACCOUNT_MEMBER_ID | ACCOUNT_HOUSEHOLD_ID |
|-------------------|----------------------|
| 27 | 54 |
| 29 | 58 |
| 31 | 62 |
| 33 | 66 |
| 35 | 70 |
| 37 | 74 |
| 39 | 78 |
| 41 | 82 |
| 43 | 86 |
| 45 | 90 |
| 47 | 94 |
| 49 | 98 |