I have 4 tables, which are linked together with a foreign key from another, eg Table 2 has fk_table1, Table 3 has fk_table2, Table 4 has fk_table3.
The first 3 tables in this chain all have corresponding data for each entry. However, Table 4 contain optional data, therefore, there may not be a corresponding entry for a field in say Table 3.
But I want those data from Table 4 too. This is currently what I have, but doesn't work.
SELECT *
FROM T1, T2, T3 LEFT JOIN T4
WHERE T1.t1 = T2.t1
AND T2.t2 = T3.t2
AND T3.t3 = T4.t3
If only T4
is optional, use LEFT JOIN
only on that table:
SELECT *
FROM T1
JOIN T2 ON T1.t1 = T2.t1
JOIN T3 ON T2.t2 = T3.t2
LEFT JOIN T4 ON T3.t3 = T4.t3
Try this:
SELECT *
FROM T1
LEFT JOIN T2 on T1.t1 = T2.t1
LEFT JOIN T3 on T2.t2 = T3.t2
LEFT JOIN T4 on T3.t3 = T4.t3
Update
Or if you want to only include rows where there is an appropriate row in T1, T2 or T3 you need to use an inner join.
SELECT *
FROM T1
INNER JOIN T2 on T1.t1 = T2.t1
INNER JOIN T3 on T2.t2 = T3.t2
LEFT JOIN T4 on T3.t3 = T4.t3
To separate the logic of table joins it's possible to use brackets:
select
*
from
t1
inner join t2 on t1.some_id = t2.some_id
inner join (
t3
left join t4 on t3.some_id = t4.some_id
) on t2.some_id = t3.some_id