查找不同表中不存在的对

Gab*_*abe 12 sql sql-server-2008

我有一个表(订单)与订单ID,位置1,位置2和另一个表(里程),位置1和位置2.

我正在使用Except操作以不在里程中的订单返回这些位置对.但我不知道如何还能返回属于这些对的相应order_id(里程表中不存在order_id).我唯一能想到的是使用外部select语句来搜索那些位置对的订单.我没试过,但我正在寻找其他选择.

我有类似的东西.

SELECT location_id1, location_id2  
FROM orders 
except
SELECT lm.origin_id, lm.dest_id
from mileage
Run Code Online (Sandbox Code Playgroud)

我怎样才能检索这些对的订单ID?

Tho*_*mas 20

您可以尝试使用Not Exists语句:

Select O.order_id, O.location_id1, O.location_id2
From orders As O
Where Not Exists    (
                    Select 1
                    From mileage As M1
                    Where M1.origin_id = O.location_id1
                        And M1.dest_id = O.location_id2
                    )
Run Code Online (Sandbox Code Playgroud)

另一种解决方案,如果你真的想使用Except

Select O.order_id, O.location_id1, O.location_id2
From Orders As O
Except
Select O.order_id, O.location_id1, O.location_id2
From Orders As O
    Join Mileage As M
        On M.origin_id = O.location_id1
            And M.dest_id = O.location_id2
Run Code Online (Sandbox Code Playgroud)

  • @JNK - 同意。在这种情况下,我通常会使用 Exists 版本而不是 except 。不过,如果他有某种理由使用 except,我提供了一种可以解决问题的替代形式。 (2认同)