且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用表中可能不存在的ID构建SQL语句?

更新时间:2023-11-26 18:16:46

外部联接在这里不起作用,因为您不想拥有table2中的所有元素,而只希望拥有表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.

想要执行以下操作:

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