SQL - 在多个表的多个列中查找缺少的条目

时间:2013-12-31 20:54:58

标签: sql oracle plsql

我有以下Oracle数据库概念:

  • Account_Household 表格,其标识列为 Account_Household_ID
  • Account_Member 表格,其标识列为 Account_Member_ID ,列为 Account_Household_ID
  • Account_Role 表,其中包含 Main_ID Support_ID 列,这些值代表* Account_Member_ID *
  • VIP_User VIP_ID ,表示 Account_Member_ID

我需要找到那些 Account_Household_IDs ,其中有 Main_ID 中没有匹配的关联 Account_Member_ID > Support_ID VIP_ID 列。我已经搜索了示例和答案,但我想我用来定义问题的搜索词并不够好。

提前致谢

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

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 |