Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto build a SQL statement with using IDs that might not be available in the table?

Using Microsoft SQL Server 2008, let's say there is a table1 that keeps the selected ids of provinces, districts, communes and villages. And then there is table2 with the ids and names of provinces, districts, communes and villages. Provinces and districts are required fields and will always be filled. Communes and villages might be filled but might even not be filled as they are not required.

What is the best way to build a dynamical SQL statement without knowing if the ids for communes and villages are filled in table1 or not.

SELECT tbl1.province, tbl1.district, tbl1.commune, tbl1.village 
  FROM dbo.table1 AS tbl1 
   AND dbo.table2 AS tbl2 
 WHERE tbl1.province = tbl2.province_id
   AND tbl1.district = tbl2.district_id 
   AND tbl1.commune = tbl2.commune_id 
   AND tbl1.village = tbl2.village_id

This statement gives wrong results if the id in table1 is not filled.

like image 654
Daniel Avatar asked Jan 22 '26 03:01

Daniel


1 Answers

An OUTER JOIN won't work here, because you don't want to have all elements from table2, but only those where a corresponding element exists in table 1.

You would want to do something like this:

SELECT tbl1.province, tbl1.district, tbl1.commune, tbl1.village 
FROM dbo.table2 AS tbl2 
INNER JOIN dbo.table1 AS tbl1
ON tbl1.province = tbl2.province_id 
AND tbl1.district = tbl2.district_id 
AND (tbl1.commune is NULL OR (tbl1.commune = tbl2.commune_id)) 
AND (tbl1.village is NULL OR (tbl1.village = tbl2.village_id))
like image 104
Daniel Hilgarth Avatar answered Jan 24 '26 18:01

Daniel Hilgarth