Web 应用程序可以发送到array of arrays
类似的函数
[
[
[1,2],
[3,4]
],
[
[],
[4,5,6]
]
]
外部数组长度为n > 0
。中间数组的长度是恒定的,在本例中为 2。内部数组长度为n >= 0
.
我可以这样构建它:
with t(a, b) as (
values (1, 4), (2, 3), (1, 4), (7, 3), (7, 4)
)
select distinct a, b
from t
where
(a = any(array[1,2]) or array_length(array[1,2],1) is null)
and
(b = any(array[3,4]) or array_length(array[3,4],1) is null)
or
(a = any(array[]::int[]) or array_length(array[]::int[],1) is null)
and
(b = any(array[4,5,6]) or array_length(array[4,5,6],1) is null)
;
a | b
---+---
7 | 4
1 | 4
2 | 3
但我想我可以像这样做得更好
with t(a, b) as (
values (1, 4), (2, 3), (1, 4), (7, 3), (7, 4)
), u as (
select unnest(a)::text[] as a
from (values
(
array[
'{"{1,2}", "{3,4}"}',
'{"{}", "{4,5,6}"}'
]::text[]
)
) s(a)
), s as (
select a[1]::int[] as a1, a[2]::int[] as a2
from u
)
select distinct a, b
from
t
inner join
s on
(a = any(a1) or array_length(a1, 1) is null)
and
(b = any(a2) or array_length(a2, 1) is null)
;
a | b
---+---
7 | 4
2 | 3
1 | 4
请注意, atext array
被传递,然后在函数内部“强制转换”。这是必要的,因为 Postgresql 只能处理匹配维度的数组,而传递的内部数组的维度可能会有所不同。我可以在传递之前通过添加一些特殊值(例如零)来“修复”它们,以使它们的长度与最长的长度相同,但我认为在函数内部处理它更干净。
我错过了什么吗?这是最好的方法吗?