在 SQL 查询中重写多个 NOT EXISTS 子句的可能方法?`
Possible way to rewrite multiple NOT EXISTS clauses in a SQL query?`
我有这个 SQL 语句,其中有很多 not exists
子句。有没有办法重写条件并避免 table 相同的 table 扫描?
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);
在上面的查询中有更多的不存在类似的方式。因为 not exists 子句具有相同的 table 来验证是否有办法将这些 not exists 组合成一种子查询。
您可以像下面这样使用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
)
您可以将各种条件组合在一起:
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);
我有这个 SQL 语句,其中有很多 not exists
子句。有没有办法重写条件并避免 table 相同的 table 扫描?
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);
在上面的查询中有更多的不存在类似的方式。因为 not exists 子句具有相同的 table 来验证是否有办法将这些 not exists 组合成一种子查询。
您可以像下面这样使用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
)
您可以将各种条件组合在一起:
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);