【问题标题】:postgres - How to efficiently find if a matching pair exists for the given tablespostgres - 如何有效地查找给定表是否存在匹配对
【发布时间】:2021-01-22 10:56:57
【问题描述】:
items
id     | name                           | group
-----------------------------------------------------------
1      | /foo/                          | app1
2      | /foo/1                         | app1
3      | /bar/2                         | app1
4      | /foo/abc/def                   | app1
5      | /foo3/                         | app2
6      | /bar3/                         | app2


mapping
id_a | id_b 
--------------
1    | 2
3    | 4

mapping.id_a and mapping.id_b have foreign key references to item.id

我需要使用 gino sqlalchemy 查找给定输入“名称”和“组”的映射表中 id_a 和 id_b 之间是否存在关联。

例子:

  1. 对于输入 '/foo/', '/foo/1', 'app1' --> 匹配成功。
  2. 对于输入 '/bar/2', '/foo/abc/def', 'app1' --> 匹配成功。
  3. 对于输入 '/foo3/'、'/bar3/'、'app2' --> 匹配失败。

【问题讨论】:

  • 什么是等效的高效的plsql查询。是通过嵌套查询还是连接?

标签: sql postgresql sqlalchemy gino


【解决方案1】:

使用连接将是微不足道的:

SELECT TRUE
FROM items AS i1
   JOIN mapping AS m ON i1.id = m.id_a
   JOIN items AS i2 ON m.id_b = i2.id
WHERE i1.name = '/foo/'
  AND i2.name = '/foo/1' AND i2.group = 'app1';

如果返回一行,则存在匹配项。

为了获得良好的性能,请创建以下两个索引(如果它们不存在):

CREATE INDEX ON item (name, group);
CREATE INDEX ON mapping (id_b);

那么你应该得到一个有效的嵌套循环连接。

【讨论】:

  • 第4行不应该是“JOIN items AS i2 ON m.id_b = i2.id”吗?
  • @LaurenzAlbe。 . .我怀疑这些组也需要匹配。
  • 我已修正错字,谢谢。 @GordonLinoff 也许。但是问题中的ids 是独一无二的,OP 没有说什么。
猜你喜欢
  • 2010-09-19
  • 1970-01-01
  • 2016-11-07
  • 2021-08-08
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
相关资源
最近更新 更多