查找传递给SQL in-clause的缺失数据

时间:2016-12-08 21:56:40

标签: sql oracle

select *  
  from Address 
 where city in ('a', 'b', 'c', 'd', 'e', 'f', ... ) 

如何修改SQL以仅获取查询中提供的上述结果中缺少的城市?

例如:我在in子句中有100个城市(硬编码),我想看看我传入的城市不在地址表中。

2 个答案:

答案 0 :(得分:4)

您可以使用union构建城市表,然后使用minus运算符。

select 'Dallas' as city from dual union all 
select 'Berlin' as city from dual union all 
select 'Cracow' as city from dual union all 
select 'Praha'  as city from dual  
minus
select city from address

您可以使用预定义类型odcivarchar2list代替联合,这会缩短语法:

select column_value as city 
  from table(sys.odcivarchar2list('Dallas', 'Berlin', 'Cracow', 'Praha'))
minus
select city from address

...而不是minus您可以使用联接或not innot exists

测试数据和两个查询的输出:

create table address (id number, city varchar2(10));
insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');

CITY
------------
Berlin
Praha

答案 1 :(得分:0)

看起来您正在寻找给定列表中不可用的所有地址。您可以使用' not in'

select *  from Address where city not in
('a',
'b',
'c',
'd',
'e',
'f'
..
)