Question

I have a query having 4 tables Table1, Table2, Table3 and Table4.

Table1 is master table having IDs
Table2 is child table with FK relationship with Table1 and has a column called Tag.
Table3 is child table with FK relationship with Table1 and has a column called Code
Table4 is child table with FK relationship with Table1 and has column called Code2

Now I want a query to represent follow logic

Select Table1.ID 
From Table1 ...
WHERE Table2.Tag IN( 1,2,3,4)
      AND ( Table3.Code In (456,789) OR Table4.CODE2 in (123,897) ) 

I know I can have join between Table1 and Table2 get the ids for which Tag value is in (1,2,3,4). But I am not sure how to join the Table3 and Table4 to achieve the requirement.

Was it helpful?

Solution

You just keep adding joins to the child table based on the condition that the Foreign Key column in each child table equals the key of Table1

You're query should look like this

Select Table1.ID 
From Table1 
JOIN Table2 ON Table2.FK_ID = Table1.ID 
JOIN Table3 ON Table3.FK_ID = Table1.ID 
JOIN Table4 ON Table4.FK_ID = Table1.ID 
WHERE Table2.Tag IN( 1,2,3,4)
AND ( Table3.Code In (456,789) OR Table4.CODE2 in (123,897) ) 

But with FK_ID replaced with the appropriate Foreign Key field

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top