我在尝试找出此查询未返回任何记录的原因时遇到问题。
我的查询如下
SELECT c.desc
FROM tableA a
INNER JOIN TableB b ON a.name = b.name
INNER JOIN TableC c ON b.id= c.Id
WHERE NOT EXISTS (SELECT 1
FROM TableC
WHERE tablec.desc IN
( SELECT DISTINCT d.desc
FROM TableD d
INNER JOIN TableE on e.Id = d.Id
)
)
AND c.active =1
AND b.active=1
现在不存在的内部查询本身返回62条记录,没有存在的外部查询返回232,但是当如上所述运行时它们返回0并且我不确定为什么。 62条记录是唯一的,232也是唯一的,现在有31条记录的重叠,所以我希望发布的查询返回201条记录,但我得到零。 很抱歉格式化,但我是通过手机发布的。
答案 0 :(得分:2)
您尚未将NOT EXISTS
中的查询与外部查询相关联,这应该使用WHERE
子句来完成,这是一个简单的示例:
SELECT *
FROM Table1 a
WHERE NOT EXISTS (SELECT 1
FROM Table2 b
WHERE a.ID = b.ID
)
虽然,我希望不过滤任何行,所以必须有另一个问题。
以下是修复查询的问题,我注意到TableE
缺少别名:
SELECT C.DESC
FROM TABLEA A
INNER JOIN TABLEB B ON A.NAME = B.NAME
INNER JOIN TABLEC C ON B.ID= C.ID
WHERE NOT EXISTS (SELECT 1
FROM TABLEC C2
WHERE C2.DESC IN (SELECT DISTINCT D.DESC
FROM TABLED D
INNER JOIN TABLEE E ON E.ID = D.ID )
AND C2.DESC = C.Desc --Relationship between inner/outer
)
AND C.ACTIVE = 1
AND B.ACTIVE = 1
最终可能会根据TableC
和TableD
之间的关系清理整个事情,可能只是简单地说:
SELECT C.DESC
FROM TABLEA A
INNER JOIN TABLEB B ON A.NAME = B.NAME
INNER JOIN TABLEC C ON B.ID= C.ID
WHERE C.DESC NOT IN (SELECT DISTINCT D.DESC
FROM TABLED D
INNER JOIN TABLEE E ON E.ID = D.ID )
)
AND C.ACTIVE = 1
AND B.ACTIVE = 1