I have a very confusing database with a table that holds two values I need in a separate table. Here is my issue:
Table1
- id
Table2
- id
- table1_id
- table3_id_1
- table3_id_2
Table3
- id
- value
I need to go from table1 and do a join that would give me back the value from table3
in two separate columns. So I want something like this:
table1.id | table2.id | table2.table3_id_1 | table2.table3_id_2 | X | Y
Where X
and Y
are the values for the row connected by table3_id_1
and table3_id_2
respectively.
Possibly make them variables or something so I can filter them in a WHERE
clause as well?
There is no need to involve
table1
.table2
has all you need - assuming there is a foreign key constraint guaranteeing referential integrity (allt2.table1_id
are actually present intable1
). Else you may want to join totable1
, thereby selecting only rows also present intable1
.I use
LEFT [OUTER] JOIN
(and not[INNER] JOIN
) to join to both instances oftable3
for a similar reason: it is unclear whether referential integrity is guaranteed - and whether any of the key columns can beNULL
. An[INNER] JOIN
would drop rows from the result where no match is found. I assume you would rather display such rows with aNULL
value for any missingx
ory
.table3.id
needs to beUNIQUE
, or we might multiply rows with several matches from eachLEFT JOIN
:If you join a table several times, use aliases to distinguish them: