查找不同表中不存在的对

时间:2011-03-28 19:36:49

标签: 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

我如何检索这些对的订单ID?

5 个答案:

答案 0 :(得分:18)

您可以尝试使用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
                    )

另一种解决方案,如果你真的想使用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

答案 1 :(得分:2)

您可以将left-outer-join连接到里程表,并且只返回不加入的行。像这样:

select O.order_id, O.location_id1, O.location_id2
from orders O left outer join mileage M1 on
  O.location_id1 = M1.origin_id and
  O.location_id2 = M1.dest_id
where M1.origin_id is NULL

答案 2 :(得分:1)

如果您想获得里程表上不存在的配对,您可以执行类似

的操作
select location_id1, location_id2
from orders
where (select count(*) from mileage 
       where mileage.origin_id = location_id1 and mileage.dest_id = location_id2) = 0

答案 3 :(得分:1)

我认为这是正如Gabe指出的那样, NOT 在SQL-Server 2008中工作:

SELECT order_id
     , location_id1
     , location_id2  
FROM orders 
WHERE (location_id1, location_id2) NOT IN
  ( SELECT origin_id, dest_id
    FROM mileage
  )

这个解决方案是否具有EXCEPT(实际上是您的原始查询和订单之间的连接)是否能够快速或可怕地工作?我不知道。

SELECT o.order_id, o.location_id1, o.location_id2  
FROM orders o
  JOIN
    ( SELECT location_id1, location_id2  
      FROM orders 
      except
      SELECT origin_id, dest_id
      FROM mileage
    ) AS g
    ON o.location_id1 = g.location_id1
    AND o.location_id2 = g.location_id2

答案 4 :(得分:0)

MySQL不支持Except。对于使用MySQL遇到这个问题的人来说,这是你如何做到的:

http://nimal.info/blog/2007/intersection-and-set-difference-in-mysql-a-workaround-for-except/