2016-09-24 38 views
0

我有一個帶有兩個表MasterTableChildrenTable的數據庫,它們之間存在一對多關係。 (當然這只是數據庫的一部分)查找主表中的子表引用記錄中的項未被其他子項引用的項目

我需要找到ChildrenTable中的記錄,它們是主表中唯一引用項目的記錄。 (例如,如果這是與Master1鏈接的唯一子節點,則需要查找Child1,但如果Child3鏈接到Master2,則不會查找Child2)。

我知道我可能已經使用子查詢做了太多,但我認爲這另一種方法會更容易:

SELECT 
    MasterTable.Name, 
    ChildrenTable.Name 
FROM 
    MasterTable INNER JOIN ChildrenTable 
    ON MasterTable.ID = ChildrenTable.MasterID 
    LEFT JOIN ChildrenTable ChildrenTable1 
    ON MasterTable.ID = ChildrenTable1.MasterID 
WHERE 
    ChildrenTable.Name = 'SomeName' 
    AND ChildrenTable.ID <> NVL(ChildrenTable1.ID,0) 
    AND ChildrenTable1.ID Is Null; 

但此查詢不給我任何結果。當我排除最後一個條件時,我得到的結果,但只有那些ChildrenTable1.ID不爲空(我已檢查數據,並有記錄應該被發現。)

我該如何解決這個問題?

回答

0

這是SQL Server的語法。不知道是否直接轉化爲Oracle的話:

SELECT MAX(ID), MasterID 
FROM ChildrenTable 
WHERE MasterID IS NOT NULL 
GROUP BY MasterID 
HAVING COUNT(1) = 1 

如果能在不同的表中存在的孩子,一個選擇可能是UNION他們:

SELECT MAX(u.ID), u.MasterID 
FROM 
(
SELECT c1.ID, c1.MasterID 
FROM ChildrenTable c1 
WHERE c1.MasterID IS NOT NULL 
UNION ALL 
SELECT c2.ID, c2.MasterID 
FROM SomeOtherChildTable c2 
WHERE c2.MasterID IS NOT NULL 
) u 
GROUP BY u.MasterID 
HAVING COUNT(1) = 1 
+0

謝謝!爲什麼'MAX'而不是'Count'? –

+0

MAX將爲您提供子行的ID,以便您知道它是哪一行(例如,可能加入它)。使用COUNT會在結果集的每一行的第一列中返回'1',因爲每行代表一組1項。 – wablab

+0

好的。爲什麼'COUNT(1)'? –

相關問題