How to can I use a SQL query column in as the arguments of a where clause?

StackOverflow https://stackoverflow.com/questions/23618826

  •  21-07-2023
  •  | 
  •  

Question

I have a query that returns a column with some records:

SELECT TAB1.COD FROM TAB1 WHERE COD > 3 AND COD < 7;

The query above would return a table like this:

_____
|COD|
|---|
| 3 |
| 5 |
| 6 |
| 7 |
-----

I would like to use the values of the column above in an another query's where clause, like this:

SELECT TAB2.ID, TAB2.FOO, TAB2.TAB1COD 
FROM TAB2 
WHERE TAB1COD = 3 OR TAB1COD = 5 OR TAB1COD = 6 OR TAB1COD = 7;

I'm not very experienced with SQL, also I'm using Oracle DB if that matters.

Thanks in advance.

Était-ce utile?

La solution

You can use IN, try this

SELECT TAB2.ID, TAB2.FOO, TAB2.TAB1COD
FROM TAB2 
WHERE TAB1COD IN (SELECT TAB1.COD 
                   FROM TAB1 
                  WHERE COD > 3 AND COD < 7)

EDIT: Also a JOIN should work for you as suggested by @sgeddes.

Autres conseils

A simple JOIN will do the trick:

SELECT t2.id, t2.foo, t2.tab1cod
FROM tab2 t2
    JOIN tab1 t1 on t2.tab1cod = t1.cod
WHERE t1.cod > 3 AND t1.cod < 7
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top