I need to write the following query. Suppose we have a table structure like this:
main_table
:
id PRIMARY KEY
column1,
column2,
column3
table_1
:
id PRIMARY KEY
main_table_id REFERENCES main_table NOT NULL,
column1,
column2,
column3
table_2
:
id PRIMARY KEY
table_1_id REFERENCES table1 NOT NULL,
necessary_column
I need to get data from the main_table
that has a given value in table_2.necessary_column
through a link to the table_1
. How can I do this?
I wrote a query for 2 tables, but I don’t know how to do this with 3 tables.
2
Answers
There are many ways. Demonstrating a query with
EXISTS
, so that you get unique rows frommain_table
:You could also just join all three tables, but that might multiply rows, and you might have to add another expensive
DISTINCT
:The question description is not very clear. So, it is hard to answer for sure. But, it seems that you need to better understand the difference between inner join and left join and that we can chain these operations.
Let’s try to use some more clear as the structure below:
Creating these tables and populating with some data
Queries
If you want to chain the relationship between these three tables that require all the connections, you can do that in any of the directions.
In other words, the result of this query:
Is the same the result of this one:
But, when we chain the queries using left join, the order of the chain makes a difference. As you can see in the following queries: