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

前端 未结 1 1739
深忆病人
深忆病人 2021-01-14 07:28

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

相关标签:
1条回答
  • 2021-01-14 08:13

    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))
    
    0 讨论(0)
提交回复
热议问题