关于在数组中搜索,我找到了一些结果/答案,但是:
WHERE = ANY
,与列一起工作,但不与subquery
一起返回一个包含数组的记录作为结果,触发错误untest
,与前2个类似的错误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}
这是一个使用IN
和unnest()
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);
您没有在样本数据中包含depth
,因此我将其替换为array_length(t1.path, 1)
,这可能就是它的样子。