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?
In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.
Variables can be assigned default values within the declaration section of a PL/pgSQL code block. This is known as default value assignment, and is done by using the assignment operator (:=) on the same line as the variable's declaration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With