棘手的SQL查询获取所有不匹配的记录

时间:2018-04-23 08:42:35

标签: sql sql-server

我需要一个棘手的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

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;