'How to join three table
I'm having three tables, two of which are same in structure
table1 like this
-----------------------------------------------
id title description image
-----------------------------------------------
1 title1 desc1 image1.png
2 title2 desc2 image2.jpg
------------------------------------------------
table2 like this
-----------------------------------------------
id title description image
-----------------------------------------------
1 ttl1 des1 img1.png
2 ttl2 des2 img2.jpg
------------------------------------------------
table 3 like this
-----------------------------------------------
id table1_id table2_id
-----------------------------------------------
1 0 1
2 1 0
------------------------------------------------
I want to join table3 to one of the other tables where id is not zero.
Solution 1:[1]
select * from table3 t3
join table1 t1 on t1.id = t3.table2_id
join table2 t2 on t2.id = t3.table1_id
Where t3.table2_id <> 0 or t3.table1_id <> 0
Use direct join with Where
Solution 2:[2]
(select * from table3 as t3 join table1 as t1 on t1.id = t3.id and t3.table1_id != 0)
UNION
(select * from table3 as t3 join table2 as t2 on t2.id = t3.id and t3.table2_id != 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | backtrack |
| Solution 2 |
