select *
from Address
where city in ('a', 'b', 'c', 'd', 'e', 'f', ... )
如何修改SQL以仅获取查询中提供的上述结果中缺少的城市?
例如:我在in子句中有100个城市(硬编码),我想看看我传入的城市不在地址表中。
答案 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 in
或not 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'
..
)