sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo crear una declaración SQL usando ID que podrían no estar disponibles en la tabla?

Una OUTER JOIN no funcionará aquí, porque no desea tener todos los elementos de la tabla 2, sino solo aquellos donde existe un elemento correspondiente en la tabla 1.

Te gustaría hacer algo como esto:

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