我有一个带有数组列的CTE,想通过该ID数组过滤另一列。
with vars as (
select
(1, 7, 10000) bubble_ids,
'Frank' name
)
select * from walruses
inner join tusks on walruses.id = tusks.walrus_id
where (
name = (select name from vars)
and tusks.bubble_id IN (select bubble_ids from vars)
);
这将产生以下内容:ERROR: operator does not exist: integer = record
我尝试过取消嵌套-unnest(bubble_ids)
-结果是ERROR: record type has not been registered
什么是正确的方法?
答案 0 :(得分:1)
(1, 7, 10000)
未定义数组。这是一个row constructor,它创建一个匿名记录(具有三个字段)。
array literal用方括号括起来,并且必须以关键字array
为前缀,例如array[1, 7, 10000]
。另外,您也可以将其写为字符串值:'{1,7,1000}'
当使用CTE作为变量/参数的“容器”时,我通常使用交叉联接使查询可以访问它。打字少
with vars as (
select
array[1, 7, 10000] bubble_ids,
'Frank' as name --<< you need the AS, because name is a keywod
)
select *
from walruses
inner join tusks on walruses.id = tusks.walrus_id
cross join vars v
where name = v.vars
and tusks.bubble_id = any(v.bubble_ids);
相对于values
,我更喜欢select
子句来定义常量值。
with vars(bubble_ids, name) as (
values (array[1, 7, 10000], 'Frank')
)
select *
from walruses
inner join tusks on walruses.id = tusks.walrus_id
cross join vars v
where name = v.vars
and tusks.bubble_id = any(v.bubble_ids);