我有四张桌子:
department有region的外键,region的Country
一个town包含其他表的3个外键,但只有一个外键应该被填充,其他表必须为空。这是因为您可以使用其Country或departement或region通过以下外键到达该镇的region。
现在,我想要做一个SQL查询,返回所有城镇及其部门、地区、国家(如果设置)。问题是我不能根据城镇的FK设置不同的连接。
怎么才能得到那份工作?
发布于 2012-11-16 12:32:34
这个怎么样:
SELECT …
FROM Town
LEFT JOIN Department ON Department.id = Town.department
LEFT JOIN Region ON Region.id = COALESCE(Town.region, Department.region)
LEFT JOIN Country ON Country.id = COALESCE(Town.country, Region.country)COALESCE从其参数中获取第一个非NULL值。因此,在本例中,来自Town的值覆盖其他设置。正如您所述,有区域引用的城镇不会有部门引用,其中只有一个应该是非NULL的,因此,如果您的数据如您所说的,订单并不重要。LEFT JOIN确保为没有匹配的表获取NULL值。如果您从国家需要的全部是它的id,您可能会忽略最后一个联接,并将COALESCE包含到您选择的值中。
发布于 2012-11-16 12:46:13
下面是一个显示值的查询。
select town.*,Department.*,Region.*,Country.* from town,Department,Region,Country where town.Dept_Id = Department.Dept and town.Region_Id = Region.Region_Id and town.Country_Id = Country.Countr_Id and Department.Region_Id = Region.Region_Id and Region.Country_Id = Country.Country_Id相反,您可以使用左联接查询。这个查询将花费更多的执行时间。左联接查询
select * from town left join Department ON Department.id = Town.department left join Region ON Region.id = coalesce (Town.region, Department.region) left join Country ON Country.id = coalesce (Town.country, Region.country)https://stackoverflow.com/questions/13416505
复制相似问题