时间:2018-11-21 05:19:02

标签: sql oracle snowflake-datawarehouse

我有这个SQL语句,其中有许多not exists子句。有没有办法重写条件并避免表相同的表扫描?

select col1,
       col2,....,colN       
from tab1
join <some join conditions> tab3
where not exists (select null
                  from tab2 p
                  where <some conditions eg: name = 'ABC'> 
                    and tab1.some_col = tab2.some_col)
  and not exists (select null
                  from tab2 p
                  where <some conditions eg: last_name = 'XYZ'> 
                    and tab1.some_col = tab2.some_col)
  and not exists (select null
                  from tab2 p
                  where <some conditions eg: country = 'PQR'> 
                    and tab1.some_col = tab2.some_col)
  and not exists (select null
                  from tab2 p
                  where <similar conditions>
                    and tab1.some_col = tab2.some_col)
  and not exists (select null
                  from tab2 p
                  where <similar conditions>
                    and tab1.some_col = tab2.some_col);

在上面的查询中,没有更多类似的方式存在。由于不存在子句具有要验证的同一张表,因此有一种方法可以将这些不存在的子句合并为一种子查询。

2 个答案:

答案 0 :(得分:1)

您可以将各种条件“或”在一起:

SELECT col1, col2,. .., colN       
FROM tab1 t1
INNER JOIN tab3 t3
    <join conditions>
WHERE NOT EXISTS (SELECT 1
                  FROM tab2 p
                  WHERE
                      (name = 'ABC' OR
                      last_name = 'XYZ' OR
                      country = 'PQR') AND
                      t1.some_col = p.some_col);

答案 1 :(得分:0)

您可以像下面一样使用in ( 'ABC','XYZ',PQR'...)

select col1,
       col2,....,colN       
   from tab1
   join <some join conditions>
  where not exists (select null
                      from tab2 p
                     where <some conditions eg: name in( 'ABC','XYZ',PQR')> 
                     and tab1.some_col = tab2.some_col
                   )