在子查询的组合中使用where子句,结果是包含数组的记录

问题描述 投票:0回答:1

关于在数组中搜索,我找到了一些结果/答案,但是:

  1. WHERE = ANY,与列一起工作,但不与subquery一起返回一个包含数组的记录作为结果,触发错误
  2. WHERE IN,也会触发相同的错误
  3. 我还在子查询上测试了untest,与前2个类似的错误
  4. 我不想检查一个值是否在数组中,而是获取/执行数组中值的查询,如WHERE IN (1,2,3,4),与其他问题/答案不同

错误:

没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

要么

没有运算符匹配int = int []

路径是int[]array类型。

结构体:

id | name |  | slug   | path | parent_id
1    name1     slug1     {1}      null
2    name2     slug2    {1,2}     1
3    name3     slug3   {1,2,3}    2
4    nam4      slug4   {4}       null

我尝试作为基础:

SELECT t.id, t.name, t.slug FROM types AS t
WHERE t.id in (SELECT t.path FROM types AS t WHERE t.id = 24)
ORDER BY depth ASC

基本上路径就像一个breadcrumb{grandparent,parent,type}

postgresql postgresql-10
1个回答
1
投票

这是一个使用INunnest()

SELECT t1.id,
       t1."name",
       t1.slug
       FROM types t1
       WHERE t1.id IN (SELECT un.e
                              FROM types t2
                                   CROSS JOIN LATERAL unnest(t2.path) un (e)
                              WHERE t2.id = 2)
       ORDER BY array_length(t1.path, 1);

运算符<@包含另一个使用该数组的数组。

SELECT t1.id,
       t1."name",
       t1.slug
       FROM types t1
       WHERE ARRAY[t1.id] <@ (SELECT t2.path
                                     FROM types t2
                                          WHERE t2.id = 2)
       ORDER BY array_length(t1.path, 1);

还有一个使用= ANY

SELECT t1.id,
       t1."name",
       t1.slug
       FROM types t1
       WHERE t1.id = ANY ((SELECT t2.path
                                  FROM types t2
                                  WHERE t2.id = 2)::integer[])
       ORDER BY array_length(t1.path, 1);

db<>fiddle

您没有在样本数据中包含depth,因此我将其替换为array_length(t1.path, 1),这可能就是它的样子。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.