Skip to content
Advertisement

How can I join 4 tables

Please help to modify the below code. I want to join these two select queries such that I can get a single output with records from two diff tables ? I have 4 tables,

table_a has the user id that I have to use to search

table_b1 has the foreign key for table_c which has the name that I want to get

table_b2 also has the foreign key for table_c which has the second name that I want to get too.

How can I combine below query in a single output?

my code

select c.name from table_a a 
join table_b1 b1 on a.id=b1.id
join table_c c on b1.pri_id=c.id where a.user='abc'

select c.name from table_a a 
join table_b2 b2 on a.id=b2.id
join table_c c on b2.pri_id=c.id where a.user='abc'

Advertisement

Answer

May be you can use UnionAll here like this,

select c.name from table_a a 
join table_b1 b1 on a.id=b1.id
join table_c c on b1.pri_id=c.id where a.user='abc'

union all

select c.name from table_a a
join table_b2 b2 on a.id=b2.id
join table_c c on b2.pri_id=c.id where a.user='abc'
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement