我需要一个棘手的SQL查询,它应该向我列出所有不匹配的目标。但是在目的地表中有亲子关系。因此,如果匹配的目的地具有不匹配的子目的地,则应列出父和子。我试图创建一个表来可视化它。我希望我能帮助理解更好的方法。
我试着写下面的查询机器人它不起作用
SELECT
*
FROM
Table_A AS ParentTable
WHERE
ID NOT IN (SELECT TableA_ID FROM Table_B WHERE TableA_ID IS NOT NULL)
-- this is to find UNmatched records
AND NOT EXISTS (
SELECT * FROM Table_A AS ChildTable
WHERE ChildTable.Parent = ParentTable.Code)
-- this is the part that I was not sure (:
这是主目的地表
TABLE A
ID Destination ParentID
1 France 0
2 Île-De-France 1
3 Ablis 2
4 Provence-Alpes-Cote D'azur 1
5 Aix-En-Provence 4
这是第二个表
TABLE B
ID Destination TableA_ID
100 France 1
101 Île-De-France 2
102 Ablis NULL
103 Provence-Alpes-Cote D'azur 4
104 Aix-En-Provence 5
在这种情况下,我需要检索下表,因为" Ablis"不匹配。
RESULTING TABLE
ID Destination ParentID
1 France 0
2 Île-De-France 1
3 Ablis 2
答案 0 :(得分:3)
您可以尝试下面的递归cte。
的 See live demo 强>
; with rcte as
(
SELECT
A.id, A.destination, A.parentid
FROM
TABLE_B b join TABLE_A a on a.destination=b.destination WHERE TableA_ID IS NULL
union all
select
T.id, T.destination, T.parentid
from
table_A T join rcte r
on r.parentid=t.id
)
select * from rcte order by parentid asc
答案 1 :(得分:1)
我会将not exist
与递归CTE
with t as (
select Id, Destination, ParentID
from table_a a
where not exists (select 1 from table_b where a.id = TableA_ID)
union all
select t.Id, t.Destination, t.ParentID
from t c join table_a a1
on t.id = c.ParentID
)
select * from t
order by 3;