在子表中查找引用主表中的记录但未被其他子项引用的项

时间:2016-09-24 13:03:21

标签: sql oracle11g null

我有一个包含两个表MasterTableChildrenTable的数据库,它们之间存在一对多的关系。 (当然这只是数据库的一部分)

我需要在ChildrenTable中查找记录,这些记录是主表中引用项目的唯一记录。 (例如,我需要找到Child1,如果它是唯一与Master1相关联的子项,但如果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不为空的那些(我已检查过数据并且应该找到记录。)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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
相关问题