查找值的PostgreSQL中数组的位置 [英] Finding the position of a value in PostgreSQL arrays
问题描述
我怎样才能在PostgreSQL中数组值的位置?有 的.index()
Python和 array_search()方法
一>为PHP函数,但我找不到任何的PostgreSQL这样的功能。我应该写一个存储函数做到这一点?我preFER通过使用内置函数来解决
How can I get the position of a value in PostgreSQL arrays? There's .index()
method for Python and array_search()
function for PHP, but I cannot find any such function for PostgreSQL. Should I write a stored function to do that? I prefer to solve by using a built-in function.
推荐答案
借助文档建议使用 generate_subscripts
功能。下面的函数的emulate的PHP的 array_search
:
The documentation recommends using the generate_subscripts
function. The function below emulate's PHP's array_search
:
CREATE FUNCTION array_search(needle ANYELEMENT, haystack ANYARRAY)
RETURNS INT AS $$
SELECT i
FROM generate_subscripts($2, 1) AS i
WHERE $2[i] = $1
ORDER BY i
$$ LANGUAGE sql STABLE;
这将返回第一个匹配的索引,如果present。如果你希望所有的比赛,只需更改返回INT
到返回SETOF INT
。这个功能,是返回 NULL
如果没有找到匹配。
This returns the index of the first match, if present. If you want all matches, simply change RETURNS INT
to RETURNS SETOF INT
. This function, as is, returns NULL
if no match is found.
此功能只适用于一维数组。
This function only works with one-dimensional arrays.
另外,请记住, array_search(NULL,A)
总是返回 NULL
,即使该数组包含空元素:
Also, bear in mind that array_search(NULL, a)
always returns NULL
, even if the array contains null elements:
> SELECT array_search(null, array[1, 2, null, 4]);
array_search
--------------
(1 row)
这是因为SQL认为 NULL = NULL
是未知的(即 NULL
)。见<一href=\"http://www.postgresql.org/docs/current/static/functions-comparison.html\">functions-comparison.如果你想 array_search
来能够找到 NULL
元素,改变
This is because SQL considers NULL = NULL
to be unknown (i.e. NULL
). See functions-comparison. If you want array_search
to be able to find NULL
elements, change
WHERE $2[i] = $1
到
WHERE $2[i] IS NOT DISTINCT FROM $1
这篇关于查找值的PostgreSQL中数组的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!