Reputation: 715
I am new to Postgresql. Please help me to solve it.
Suppose I have three table called 'table_1', 'table_2' & 'table_3'
I want to get data from table_3 that is related to table_1 and table_2
Such as I am retrieving value_1 and value_2 from table_1 and table_2
Query 1:
Select value_1 From table_1
Query 2:
Select value_2 From table_2
Now I want to use these values in table_3
Query 3:
Select * from table_3 where column_1 = value_1 and column_2 = value_2
How to store first 2 values in variables and use it in third query?
Upvotes: 19
Views: 25888
Reputation: 399
You can use the following query:
with v1 as (select value_1 from table_1),
v2 as (select value_2 from table_2)
select * from table_3 where column_1 = (select value_1 from v1)
and column_2 = (select value_2 from v2);
If v1 and v2 are having multiple rows you can use 'in' operator instead of '=' operator.
For more information, please check the PostgreSQL documentation here.
You can also check a post similar to this on Stackoverflow here.
Upvotes: 24