5

考虑表 Address ,其中包含 Country、State 和其他数据字段。我想获取除 Country,State 组合为 (US, IL), (US,LA), (IND,DEL) 的所有记录

查询就像

Select * from Address a 
where not exists 
(
   select Country,State 
   (select 'US' as Country, 'IL' as State 
     union
   select 'US' as Country, 'LA' as State 
     union
    select 'IND' as Country, 'DEL' as State 
  ) e
 where e.Country != a.Country and e.State != a.state
)

如何轻松实现(用简单的子查询替换国家,联合状态组合)?由于总数据不是很大,我现在最不关心性能。


我知道我可以创建表变量,使用插入语法在其中添加所有文字组合,并使用表变量表示不存在,但我觉得这对于小要求来说是多余的(不存在于 2 个变量上)。

4

3 回答 3

6

看起来您的查询试图这样做:

select * 
from Address a 
where not exists (
                 select *
                 from (
                      select 'US' as Country, 'IL' as State union all
                      select 'US' as Country, 'LA' as State union all
                      select 'IND' as Country, 'DEL' as State 
                      ) e
                 where e.Country = a.Country and 
                       e.State = a.State
                 )

或者你不能使用派生表并且仍然得到相同的结果

select *
from Address as a
where not (
          a.Country = 'US' and a.State = 'IL' or
          a.Country = 'US' and a.State = 'LA' or
          a.Country = 'IND' and a.State = 'DEL'
          )
于 2013-11-14T17:55:30.327 回答
2

只需在查询中直接使用值:

-- Sample data.
declare @Table as Table ( Country VarChar(6), State VarChar(6), Foo VarChar(6) );
insert into @Table ( Country, State, Foo ) values
  ( 'US', 'IL', 'one' ), ( 'XX', 'LA', 'two' ), ( 'IND', 'XXX', 'three' ), ( 'IND', 'DEL', 'four' );

select * from @Table;

-- Demonstrate excluding specific combinations.
select T.*
  from @Table as T left outer join
    ( values ( 'US', 'IL' ), ( 'US', 'LA' ), ( 'IND', 'DEL' ) ) as Exclude( Country, State )
    on T.Country = Exclude.Country and T.State = Exclude.State
  where Exclude.Country is NULL;
于 2013-11-14T18:22:22.237 回答
1

或者

select * 
from Address a 
left outer join
    ( select 'US' as Country, 'IL' as State 
        union select 'US', 'LA'  
        union select 'IND', 'DEL'  ) as n
    on a.Country = n.Country and a.State = n.State
  where n.Country is NULL;
于 2013-11-14T18:36:03.783 回答