问题描述
我需要将列传递给子查询以进行过滤,但是我似乎无法使其正常工作。
我知道,如果我的子查询要返回单个列,那么我可以重新排列查询,这样就可以了,但是我需要子查询返回3列。
到目前为止,这是我的查询,它在抱怨:
where c.location.Stdistance(l.location) is not null
order by c.Location.Stdistance(l.location)
使用
无法绑定多部分标识符“ l.location”。
select
l.*,city.*
from
listings l,(select top 1 c.UnicodeName,c.name,r.code as region,cn.code as country
from cities c
inner join regions r on r.regionid = c.regionid
inner join Countries cn on cn.CountryId = r.countryid
where c.location.Stdistance(l.location) is not null
order by c.Location.Stdistance(l.location)) as city
实际计划 https://www.brentozar.com/pastetheplan/?id=BkiRk-74P
城市和商家信息索引
CREATE SPATIAL INDEX [256_HHHH] ON [dbo].[Listings]
(
[Location]
)USING GEOGRAPHY_GRID
WITH (GRIDS =(LEVEL_1 = HIGH,LEVEL_2 = HIGH,LEVEL_3 = HIGH,LEVEL_4 = HIGH),CELLS_PER_OBJECT = 256,PAD_INDEX = OFF,STATISTICS_norECOmpuTE = OFF,SORT_IN_TEMPDB = OFF,DROP_EXISTING = OFF,ONLINE = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE SPATIAL INDEX [16_HHHH] ON [dbo].[Listings]
(
[Location]
)USING GEOGRAPHY_GRID
WITH (GRIDS =(LEVEL_1 = HIGH,CELLS_PER_OBJECT = 16,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
解决方法
您要描述的是横向联接,其中联接的子查询使用listing
表中的列。由于from
子句中的逗号,此操作失败:某些数据库的确可以识别这种隐式横向联接,但不能识别SQL Server。
您必须明确说明连接类型(无论如何都是最佳做法):使用cross apply
。
select l.*,city.*
from listings l
cross apply (
select top (1) c.UnicodeName,c.name,r.code as region,cn.code as country from cities c
inner join regions r on r.regionid = c.regionid
inner join Countries cn on cn.CountryId = r.countryid
where c.location.STDistance(l.location) is not null
order by c.Location.STDistance(l.location)
) as city