在SQL Server中选择文字作为表数据

时间:2013-11-14 17:32:57

标签: sql sql-server tsql where-clause

考虑表地址,包括字段Country,State和其他数据字段。我希望获得所有记录,除了那些国家,国家组合为(美国,IL),(美国,洛杉矶),(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
)

如何轻松实现(用简单的子查询替换coutry,union的组合)?由于总数据不是很大,我现在对性能最不感兴趣。


我知道我可以创建表变量,使用insert into语法添加所有文字组合,并使用表变量不存在,但我觉得它对于小要求是不合适的(2个变量上不存在)。

3 个答案:

答案 0 :(得分:5)

您的查询似乎尝试执行此操作:

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'
          )

答案 1 :(得分: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;

答案 2 :(得分:0)

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

-- 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;