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

試著忘記壹切 提交于 2019-12-01 08:58:57

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