Change IN to EXISTS in SQL

I have the following query:

select A,
       B 
  from table1 
 where A in (select c 
               from table 2
            )

However, now I need to change this query and use existsinstead of in, it should give the same result. My form looks like this:

table1            table2
A    B               c
------             -----
1    x               1
2    y               3
3    z               4
4    w               7
5    a
1    b

How to use existsfunctions?

You need to match existsthe two columns that will be used in:

select
    t1.a, t1.b
from
    table1 t1
where
    exists (select 1 from table2 t2 where t2.c = t1.a)

The reason this has to be done is because existsa semi-join is performed on the tables and thus needs to have a join condition.

This will be achieved by a direct inner join.

 select 
    t1.a, t1.b
 from 
    table1 as t1 
       inner join table2 as t2 on t1.a=t2.c 

Change the expression:

FROM Table1 WHERE a IN( SELECT c FROM Table2 )

EXISTSJust a quick question:

  1. Add SELECTaWHERE
    FROM Table1 WHERE a IN( SELECT c FROM Table2 WHERE )
    
  2. Move the outer match column (a) into the SELECTinner WHEREclause
    FROM Table1 WHERE  IN( SELECT c FROM Table2 WHERE a )
    
  3. Move the inner matching column (b) to WHEREthe clause, leaving the column placeholder (constant or *):
    FROM Table1 WHERE  IN( SELECT * FROM Table2 WHERE a = c )
    
  4. willIN change to EXISTS:
    FROM Table1 WHERE EXISTS( SELECT * FROM Table2 WHERE a = c )
    
  5. To be on the safe side, add the table name to the inner column:
    FROM Table1 WHERE EXISTS( SELECT * FROM Table2 WHERE a = Table1.c )

おすすめ

転載: blog.csdn.net/weixin_43167662/article/details/129912114