【问题标题】:How can I get all the related rows when using IN to filter?使用 IN 过滤时如何获取所有相关行?
【发布时间】:2022-02-12 08:03:49
【问题描述】:

这是我的查询的样子:

select "spaces"."id" as "id",
  "spaces"."user_id" as "user_id",
  "spaces"."type" as "type",
  "spaces"."latitude" as "latitude",
  "spaces"."longitude" as "longitude",
  "categories"."category_id" as "categories:category_id"
  from "spaces"
  left join "spaces_categories" as "categories" on "categories"."space_id" = "spaces"."id"
  where "categories"."category_id" in ($)
  and ST_DWithin(spaces.geometry::geography, ST_SetSRID(ST_Point($,$), 4326)::geography, $)

我正在使用第 14.1 页

我正在尝试查找半径内满足请求类别 ID 的所有空间,以及这些空间的所有类别。

一个空间可以有很多类别 ID,所以如果我搜索类别 ID (1,2),并且恰好有 2 个空间结果(假设每个空间有 4 个类别,1,2,3,4),我会期待 8 行.但是,对于类别 1,2,我的查询仅返回 4 行。

如何更新我的查询,以便获得所有类别,只要有一些重叠?

是因为我的IN 子句吗?

【问题讨论】:

  • 查询格式错误。谓词where "categories"."category_id" in ($) 默默地将外连接转换为内连接。请通过以下方式修改查询:1) 使用内部联接,或 2) 通过接受 "categories"."category_id" 中的空值。
  • 谢谢,抱歉,您能解释一下修改查询的意思吗?您是说将 where 向下移动(在 postgis 函数之前),然后使用,所以它在连接上?
  • I am trying to find spaces within a radius, and that meet some categories input.get all the categories, as long there is some overlap 不同。请确切地说明您想要什么。首先公开你的 Postgres 版本。
  • 啊,我明白了,谢谢!我已经更新了

标签: sql postgresql join postgis


【解决方案1】:

EXISTS 子查询应该可以解决问题:

SELECT s.id
     , s.user_id
     , s.type
     , s.latitude
     , s.longitude
     , c.category_id AS "categories:category_id"
FROM   spaces                 s
LEFT   JOIN spaces_categories c ON c.space_id = s.id
WHERE  st_dwithin(s.geometry::geography, st_setsrid(st_point($,$), 4326)::geography, $)
AND    EXISTS (
   SELECT FROM spaces_categories x
   WHERE  x.space_id = s.id
   AND    x.category_id IN ($)
   );

还有很多其他的方法,但这应该是最快最清晰的。

不过,从geometrygeography 的演员阵容似乎令人担忧。你有一个表达式 index 覆盖它吗?

相关:

【讨论】:

  • 谢谢!从几何到地理的转换是因为我不了解 postgis,我应该使用地理列,因为我将在一个点的米内或边界框内进行查询。几何允许我以度数查询。您认为我更改列更好吗?我没有表达式索引,只有列 gist 索引。
  • 如果可以,请切换到geography。如果你不能,至少添加一个或多个表达式索引来覆盖你的主要查询。我添加了相关链接。您拥有的普通索引不会帮助手头的查询。
  • 我明白了。非常感谢,今天学习了表情索引。非常感谢
猜你喜欢
  • 2021-05-02
  • 2023-03-16
  • 2015-10-12
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 2020-08-07
相关资源
最近更新 更多