1

我有一个名为 MapObjects 的表,用于存储有关放置在地图上的对象的信息。我有另一个名为 OrgLocations 的表,用于存储组织所在的所有位置。位置用纬度和经度定义。最后,我还有另一个名为 ObjectLocations 的表,它将地图对象映射到 OrgLocations 表中的组织。它用于指示地图上显示的对象的位置子集。

例如,假设一个组织 (OrgID = 10) 有 4 个位置(存储在 OrgLocations 表中):达拉斯、亚特兰大、迈阿密、纽约。该组织有 1 个与亚特兰大和迈阿密关联的地图对象 (MapObjects.ID = 5)。

我的数据集必须从 OrgLocations 返回与亚特兰大和迈阿密(但不包括达拉斯或纽约)相对应的记录。但是,我也可以有一个未分配给任何位置的地图对象(ObjectLocations 中没有记录)。这些地图对象仍然属于一个组织,但不与任何特定位置相关联。在这种情况下,我想返回分配给组织的所有位置。

我不确定这是否是通过条件连接或 WHERE 子句中的某些内容来完成的。以下是表格与一些数据的样子:

组织地点

ID   OrgID     Latitude      Longitude     Name
0     10        32.780        -96.798      Dallas
1     10        33.7497       -84.394      Atlanta
2     10        25.7863       -80.2270     Miami
3     10        40.712        -74.005      New York
4     11        42.348        -83.071      Detroit

对象位置

OrgLocationID      MapObjectID
1                      5
2                      5

地图对象

ID      OrgID
5        10
6        11

在此示例中,当 MapObjects.ID 为 5 时,ObjectLocations 中存在此对象的 2 个位置:亚特兰大和迈阿密。当 MapObjects.ID 为 6 时,ObjectLocations 中没有记录,因此返回 OrgLocatons 中属于组织 (OrgID = 11) 的所有位置。

谢谢你的帮助!

4

1 回答 1

2

如果您检查是否存在MapObjectIDin ObjectLocations来决定使用什么查询,我想您将获得最干净的查询。

像这样的东西:

declare @MapObjectID int
set @MapObjectID = 5

if exists(select * 
          from ObjectLocations 
          where MapObjectID = @MapObjectID)
begin
  select *
  from OrgLocations
  where ID in (select OrgLocationID 
               from ObjectLocations
               where MapObjectID = @MapObjectID)
end
else
begin
  select *
  from OrgLocations
  where OrgID in (select OrgID
                  from MapObjects
                  where ID = @MapObjectID)
end

作为单个查询。

select OL.*
from OrgLocations as OL
  inner join ObjectLocations as OLoc
    on OL.ID = OLoc.OrgLocationID
where OLoc.MapObjectID = @MapObjectID
union all
select OL.*
from OrgLocations as OL
  inner join MapObjects as MO
    on OL.OrgID = MO.OrgID
where MO.ID = @MapObjectID and
      not exists (select *
                  from ObjectLocations
                  where MapObjectID = @MapObjectID)
于 2012-04-30T08:13:52.127 回答