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

梦想的初衷 提交于 2019-12-01 06:25:34

问题


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.


回答1:


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))


来源:https://stackoverflow.com/questions/6185987/howto-build-a-sql-statement-with-using-ids-that-might-not-be-available-in-the-ta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!