简体   繁体   中英

How to combine 2 SQL statements into a single statement

Imagine that I have a table with info regarding a person (1 line per person) lets call it TableA , now i want to for example to get all the persons that have debts in TableB and also Credit to pay Monthly in TableC .

Now having this done by 2 commands is easy, a simple:

SELECT * 
  FROM TableA 
 WHERE ID IN (SELECT ID 
                FROM TABLEB 
               WHERE Header1=false);

SELECT * 
  FROM TableA 
 WHERE ID IN (SELECT ID 
                FROM TABLEC 
               WHERE Header2=false);

But i don't want to make 2 separate commands to return 2 separate datatables, isn't it possible to join them together instead and get it all merged down without duplicates? Something like:

SELECT * 
  FROM TableA 
 WHERE ID IN (SELECT ID 
                FROM TABLEB 
               WHERE Header1=false 
                 AND 
              SELECT ID 
                FROM TABLEC 
               WHERE Header2=false);

If this is possible, what would be the right syntax?

Why not use a UNION ?

SELECT ...
FROM tableA
WHERE id IN (
   SELECT id from tableB...
   UNION ALL <---note this
   SELECT id from tableC...
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM