将 where 子句与子查询结合使用,结果是包含数组的记录
Using a where clause in a combination with a subquery which result is a record containin an array
我找到了一些 results/answers,关于在数组中搜索,但是:
WHERE = ANY
,适用于列,但不适用于 subquery
,结果 returns 一个包含数组的记录,触发错误
- WHERE IN,同样触发同样的错误
- 我还在子查询上测试了
untest
,与第一个 2 类似的错误
- 我不想检查某个值是否在数组中,但 get/execute 查询数组中的值,例如
WHERE IN (1,2,3,4)
,而不是另一个 questions/answers
错误:
No operator matches the given name and argument types. You might need
to add explicit type casts.
或
No operator matches int = int[]
路径是一个int[]
数组类型。
结构:
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)
,这可能就是它的原样。
我找到了一些 results/answers,关于在数组中搜索,但是:
WHERE = ANY
,适用于列,但不适用于subquery
,结果 returns 一个包含数组的记录,触发错误- WHERE IN,同样触发同样的错误
- 我还在子查询上测试了
untest
,与第一个 2 类似的错误
- 我不想检查某个值是否在数组中,但 get/execute 查询数组中的值,例如
WHERE IN (1,2,3,4)
,而不是另一个 questions/answers
错误:
No operator matches the given name and argument types. You might need to add explicit type casts.
或
No operator matches int = int[]
路径是一个int[]
数组类型。
结构:
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)
,这可能就是它的原样。