来自2个表的SQL查询

时间:2010-08-06 17:15:32

标签: sql oracle10g

我目前有两个看起来像这样的表:

表1

Id | AddressNumber | AddressStreet | AddressZip
------------------------------------------------
1   | 50           | Fake          | 60101
2   | 300          | Fake          | 60101
3   | 50           | Fake2         | 60101
4   | 50           | Fake          | 60103

表2

AddressLowRange | AddressHighRange | AddressStreet | AddressZip
---------------------------------------------------------------
50             | 200              | Fake          | 60101
20             | 50               | Other Fake    | 70102

我需要从表1中找到Ids列表,其中地址不在表2中。 因此,对于上面的示例数据,我会回到ID 2,3和& 4。

4 个答案:

答案 0 :(得分:9)

试试这个。

SELECT Id
FROM Table1
WHERE NOT EXISTS
    (SELECT *
    FROM Table2
    WHERE Table1.AddressNumber BETWEEN Table2.AddressLowRange AND Table2.AddressHighRange
        AND Table1.AddressStreet = Table2.AddressStreet
        AND Table1.AddressZip = Table2.AddressZip
    )
;

答案 1 :(得分:1)

地址不在表2中是指addressStreet

如果是这样的话:

select id from table1 where addressStreet not in (select distinct addressstreet from table2)

select * from table1 where addressStreet not in (select distinct addressstreet from table2)

所有字段

答案 2 :(得分:1)

select id from "Table 1"
where AddressStreet not in (select distinct AddressStreet from "Table 2")

答案 3 :(得分:1)

我假设您要考虑数字范围,与大多数其他答案不同。这样的事情应该有效:

select Id
  from Table1
 where Id not in (select T1.Id
                    from Table1 T1
                    join Table2 T2 on (T1.AddressNumber between T2.AddressLowRange and T2.AddressHighRange)
                                   and T1.AddressStreet = T2.AddressStreet
                                   and T1.AddressZip = T2.AddressZip)

或略微简化......

select T1.Id
  from #table1 T1
  left join #table2 T2 on (T1.AddressNumber between T2.AddressLowRange and T2.AddressHighRange)
                      and T1.AddressStreet = T2.AddressStreet
                      and T1.AddressZip = T2.AddressZip
 where T2.AddressLowRange is null