【问题标题】:T-SQL - passing column to subquery for filteringT-SQL - 将列传递给子查询以进行过滤
【发布时间】:2020-09-06 23:53:05
【问题描述】:

我需要将一列传递给子查询进行过滤,但我似乎无法让它工作。

我知道如果我的子查询要返回一个列,那么我可以重新排列我的查询并且它会起作用,但我需要子查询返回 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,LEVEL_2 = HIGH,LEVEL_3 = HIGH,LEVEL_4 = HIGH), 
CELLS_PER_OBJECT = 16, 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

【问题讨论】:

  • 您别名为city 的子查询几乎感觉它属于select 子句。
  • 我试过了,但是一旦它在选择它抱怨子查询必须只返回一列,而我的返回 3 (city.*)

标签: sql-server tsql join sql-order-by


【解决方案1】:

您所描述的是横向连接,其中连接的子查询使用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

【讨论】:

  • 这很有效,但速度很慢,53 秒就可以完成 12k 个列表。我附上了执行计划,但我不知道我能做些什么来改进它。我在列表和城市表上都有 2 个空间索引(也用这些索引编辑了主帖)
猜你喜欢
  • 2020-03-08
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
相关资源
最近更新 更多