【问题标题】:SQL Server where query not working after join and new column连接和新列后查询不起作用的 SQL Server
【发布时间】:2021-01-05 03:33:04
【问题描述】:

这是我当前的工作查询:

DECLARE @ProductName AS VARCHAR(400) 

SET @ProductName = 'water'
SET @ProductName = CONCAT('\"',@ProductName,'\"') 

SELECT 
    *,
    distance = GEOGRAPHY::Point(42, -90, 4326).STDistance(GEOGRAPHY::Point(latitude, longitude, 4326)) / 1609.344 
FROM 
    products AS FT_TBL 
INNER JOIN 
    FREETEXTTABLE(products, product_name, @ProductName) AS KEY_TBL ON FT_TBL.id = KEY_TBL.[key] 
WHERE 
    KEY_TBL.RANK >= 10 
ORDER BY 
    KEY_TBL.RANK DESC, distance ASC
        

我正在尝试在加入之前添加对 distance < 20 的检查,但无论我做什么都无法正常工作,我收到一个错误

列名“距离”无效

即使我在 where 查询中尝试。

我什至在加入之前如何才能有效地做到这一点?

【问题讨论】:

  • 把它放在一个子查询中。顺便说一句:@BrentOzar Why Full Text’s CONTAINS Queries Are So Slow 可能对此很感兴趣
  • 感谢您的链接,但不感谢您的无益建议
  • 你觉得它有什么没有帮助的地方?我相信它与接受的答案相同

标签: sql sql-server azure-sql-database


【解决方案1】:

您需要先使用子查询来实际创建具有distance 列的表,然后再将其包含在where 子句中。

SELECT * FROM (
SELECT *,
distance = GEOGRAPHY::Point(42, -90, 4326).STDistance(GEOGRAPHY::Point(latitude, longitude, 4326)) / 1609.344 
FROM products ) AS FT_TBL 
INNER JOIN FREETEXTTABLE(products, product_name, @ProductName) AS KEY_TBL ON FT_TBL.id = KEY_TBL.[key] 
WHERE KEY_TBL.RANK >= 10 AND distance < 20 ORDER BY KEY_TBL.RANK DESC ,distance asc

这应该可以正常工作。

【讨论】:

  • 你能告诉我我对子查询不熟悉吗
  • 你不能在where子句中包含distance列,这样想,where是一个过滤语句,它过滤你想要的数据,所以它不能过滤不存在​​的东西然而。但是使用子查询,您已经使用distance 列创建了一个“表”,因此可以将其放在where 子句中。
猜你喜欢
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 2018-07-11
相关资源
最近更新 更多