查找表中不存在的值

时间:2016-10-26 15:29:44

标签: sql oracle

说我有一张桌子:

ID   ACCNT   DESC
1    123     aaa
2    234     bbb
3    345     ccc

我有一个帐号123,345,555,777的清单 所以我可以通过

获得一个列表
SELECT * FROM MY_TABLE WHERE ACCNT IN (...my list...)

现在我想完成相反的事情 从我的列表中我想要一个查询来向我显示表中没有的帐号。

因此,在我的示例中,我想报告表中不存在555和77。

如何在Oracle SQL中编写此查询?

6 个答案:

答案 0 :(得分:3)

select column_value as missing_num
from   table (sys.odcinumberlist (123,345,555,777))
where  column_value not in (select accnt from my_table);

答案 1 :(得分:1)

这是一种方法。您可以简单地创建模式级集合(嵌套表)并使用右/左外连接:

-- our collection type
create type t_list as table of number;
/

-- sample of data from your question
with t1(id1, accnt, desc1) as(
  select 1, 123, 'aaa' from dual union all
  select 2, 234, 'bbb' from dual union all
  select 3, 345, 'ccc' from dual
)
-- query itself
select t2.column_value as missing_num
  from t1                               <-- here goes your table
  right join table(t_list(123,345,555,777)) t2
     on (t2.column_value = t1.accnt)
  where t1.accnt is null 

结果:

MISSING_NUM
-----------
        555
        777

2 rows selected.

答案 2 :(得分:1)

这取决于您的帐号列表的来源。例如,您可以使用集合类型和TABLE运算符:

-- Test case setup
CREATE TABLE ACCNT(ID,ACCNT,DESCR) AS
SELECT 1,123, 'aaa' FROM DUAL UNION ALL
SELECT 2,234, 'bbb' FROM DUAL UNION ALL
SELECT 3,345, 'ccc' FROM DUAL;

-- Create a collection type to hold account numbers
CREATE TYPE tab_numbers AS TABLE OF NUMBER;
/

-- Select account numbers that does not occur on the table
SELECT *
  FROM TABLE(TAB_NUMBERS(123,345,555,777))
 WHERE COLUMN_VALUE NOT IN (SELECT ACCNT FROM ACCNT);

答案 3 :(得分:0)

以下方法可能适用于Oracle。您可以使用UNION创建子查询,该子查询包含一个包含您的帐户ID列表的列。然后,您可以LEFT JOIN将此MY_TABLE添加到您的表中,并隔离与SELECT t1.ACCNT FROM ( SELECT 123 AS ACCNT FROM DUAL UNION ALL SELECT 345 FROM DUAL UNION ALL SELECT 555 FROM DUAL UNION ALL SELECT 777 FROM DUAL ) t1 LEFT JOIN MY_TABLE t2 ON t1.ACCNT = t2.ACCNT WHERE t2.ACCNT IS NULL 中的任何内容不匹配的ID。

### Start of script (store list of existing variable names)
$ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name

<#
Script contents go here
#>

### End of script (remove new variables)
$NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
if ($NewVariables)
    {
    Write-Host "Removing the following variables:`n`n$NewVariables"
    Remove-Variable $NewVariables
    }
else
    {
    Write-Host "No new variables to remove!"
    }

这种方法的一个优点是它实际上并不会创建一个在查询后可能不需要的表。

答案 4 :(得分:0)

您可以使用WHERE NOT EXISTS,下面提供示例;

SELECT *
FROM MY_TABLE MT 
WHERE NOT EXISTS (SELECT * FROM AccountNumbers AN WHERE MT.accountID = AN.id)

答案 5 :(得分:0)

一种方法是使用取消旋转功能:

select Number as ACCNT from(
select * from (
select 123,345,555,777 from dual ) 
unpivot
(
  "Values" FOR "Number" IN ("123","235","555","777")
 ) 
 ) 
minus

select ACCNT from my_table ;

输出应该是列表中剩下的帐号。

相关问题