如何有效检查列是否包含给定值?

问题描述 投票:0回答:2

我有一个表

TBL1
,其中包含列,其中
COL1

我想尽可能高效地检查(快速计算,小结果)是否在

"foo"
中找到值
"bar"
"bar2"
COL1
,并报告丢失的值。

我该怎么做?

版本是“19.00.0000”,表结构和索引可能会有所不同,因为这意味着要应用于各种情况(即

COL1
可能会被索引或不被索引)。

sql oracle
2个回答
2
投票

将您的话放入您 LEFT JOIN tbl1 的单独表/cte 中。比如:

with cte (c1) as (select 'foo' from dual
                  union all
                  select 'bar' from dual
                  union all
                  select 'bar2' from dual)
select c1
from cte
left join tbl1 on cte.c1 = tbl1.col1
where tbl1.col1 is null;

确保有 tbl1.col1 索引。

演示:https://dbfiddle.uk/mjAU2YPP


2
投票

另一种选择是使用

minus
集合运算符:

SQL> WITH
  2     tbl1 (col1)                      --> this is your table (you don't
  3     AS                                   have to type it here, as a CTE)
  4        (SELECT 'foo' FROM DUAL         
  5         UNION ALL
  6         SELECT 'xyz' FROM DUAL),
  7     cte (c1)                         --> this is table that contains
  8     AS                               --  values you're checking; could
  9        (SELECT 'foo' FROM DUAL       --  be "real" table, or a CTE as in 
 10         UNION ALL                    --  this example
 11         SELECT 'bar' FROM DUAL
 12         UNION ALL
 13         SELECT 'bar2' FROM DUAL)
 14  SELECT c1 FROM cte                  --> finally, the query itself
 15  MINUS
 16  SELECT col1 FROM tbl1;

C1
----
bar
bar2

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