【发布时间】:2016-09-24 13:03:20
【问题描述】:
我有一个包含两个表MasterTable 和ChildrenTable 的数据库,它们之间是一对多的关系。 (当然这只是数据库的一部分)
我需要在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 不为空的那些(我检查了数据,应该找到记录。)
我该如何解决这个问题?
【问题讨论】: