所以我有三张桌子......结构如此
LocationID LocationName
1 Location 1
2 Location 2
3 Location 3
SubAreaID LocationID SubAreaName
1 1 SubName1
2 1 SubName2
3 2 SubName3
4 2 SubName4
SubAreaID LocationID UserName
1 1 Bob
2 1 Frank
3 2 Jeff
null 3 Dave
每个细节都必须有一个位置
理想情况下,结果如下所示。我将如何构建查询?
LOCATION NAME SUB AREA NAME USERNAME
Location 1 SubName1 Bob
Location 1 SubName2 Frank
Location 2 SubName3 Jeff
Location 2 SubName4 null
Location 3 null Dave
真正让我失望的事情是空置的可能性
SELECT a.LocationID, a.LocationName, b.SubAreaID, b.SubAreaName, c.UserName
FROM Location a
JOIN SubArea b ON a.LocationID = b.LocationID
FULL JOIN Detail c ON a.LocationID = c.LocationID
然而,这不会产生预期的结果。有什么意见吗?
答案 0 :(得分:0)
试试这个
SELECT a.LocID, a.LocName, b.SubAreaID, b.SubAreaName, c.UserName
FROM Location a
LEFT JOIN SubArea b ON a.LocID = b.LocID
OUTER APPLY (SELECT c.UserName
FROM Details c
WHERE a.LocID = c.LocID
AND (c.SubAreaID = b.SubAreaID OR B.SubAreaId IS NULL)
) as c
编辑:使用OUTER APPLY尝试此查询。
另请查看[ SQL FIDDLE ](sqlfiddle.com/#!3/b4bce/5ce/5)进行演示。
答案 1 :(得分:0)
使用“LEFT JOIN”替换这些单词而不是JOIN和FULL JOIN。
JOIN要求某个地点有一个子区域显示在结果中。
FULL JOIN将从双方获取数据,即使没有匹配值。