一个 Web 应用程序可以发送一个类似以下的 数组的数组
给函数:
[
[
[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
请注意,传递了一个“text数组”,然后在函数内部进行了“转换”。这是必要的,因为Postgresql只能处理匹配维度的数组,而传递的内部数组可能维度不同。我可以通过添加一些特殊值(如零)来“修复”它们,使它们的长度都与最长的长度相同,但我认为在函数内部处理这个问题会更加清晰。我有什么遗漏吗?这是最佳方法吗?