从'in'查询列表中获取表中不存在的记录

问题描述 投票:1回答:1

我正在使用一个带有'in'子句的查询,在oracle 11g中有大约500条记录,是否有任何方法可以从'in'子句中获取其值不在表中的记录。

例:

查询:

select * from table where name in('NICK','TOM','LUCY','HARRY','RAFEL');

样本表:

enter image description here

在上表中,'TOM','HARRY','RAFEL'的记录在表中没有出现在in子句中,所以输出应该是:

TOM

HARRY

RAFEL
sql oracle
1个回答
3
投票

您可以使用您要查找的值声明一个集合,然后使用您的参照表执行连接以搜索不匹配的记录:

with cte_in as  (
select 'NICK' nickname from dual
union all select 'TOM' from dual
union all select 'LUCY' from dual
union all select 'HARRY' from dual
union all select 'RAFEL' from dual
)
SELECT    nickname 
FROM      cte_in cte
LEFT JOIN mytable mt
       ON cte.nickname = mt.NAME
WHERE     mt.NAME IS NULL 

其他解决方案是使用MINUS

SELECT nickname
FROM   cte_in
minus
select name 
from   mytable

编辑:另一个接近IN格式的解决方案

WITH cte_in
     AS ( SELECT ( column_value ).getstringval() nickname
          FROM   XMLTABLE('"NICK","TOM","LUCY","HARRY","RAFEL"') ) 
SELECT *
FROM   cte_in
minus
SELECT NAME
FROM   mytable; 

见小提琴:http://sqlfiddle.com/#!4/679ae/11

© www.soinside.com 2019 - 2024. All rights reserved.