【问题标题】:is there a way to preserve order or array when using ANY in postgres query?在 postgres 查询中使用 ANY 时,有没有办法保留顺序或数组?
【发布时间】:2021-05-01 10:30:00
【问题描述】:

我希望能够使用ANY 进行查询,以维护传递给任何函数的数组的顺序。考虑这个简单的例子:

create table stuff (
    id serial,
    value int
);
insert into stuff (value) values (1), (2), (3), (4), (5);

select * from stuff where value = ANY(ARRAY[1,2,3,4,5]);
select * from stuff where value = ANY(ARRAY[5,4,3,2,1]);

这导致两个查询的顺序相同,即使数组的顺序不同。

----+-------
  1 |     1
  2 |     2
  3 |     3
  4 |     4
  5 |     5
(5 rows)

 id | value 
----+-------
  1 |     1
  2 |     2
  3 |     3
  4 |     4
  5 |     5
(5 rows)

如果可能的话,我想有一种速记方法,以在ANY 内按数组顺序保存结果。这可能吗?

到目前为止,我不得不写这样的东西,感觉有点笨拙:


CREATE FUNCTION ordered_any (
 ints int[]
) RETURNS int[] as $$
DECLARE
   results int[];
   i int;
   value int;
BEGIN
  FOR i IN 1 .. cardinality(ints) LOOP
    SELECT f.id FROM stuff f 
      WHERE f.value = ints[i]
    INTO value;
    results = array_append(results,  value);
  END LOOP;

  RETURN results;
END;
$$
LANGUAGE 'plpgsql';

select ordered_any(ARRAY[5,4,3,2,1]);

感谢“任何”帮助!没有双关语;)

【问题讨论】:

  • 如果需要有序的结果,需要使用ORDER BY ...
  • @Luuk 不是ORDER BY 表中的任何内容,而是ANY 内部的数组,您对此有什么想法吗?

标签: sql arrays postgresql


【解决方案1】:
select 
   id,
   value, 
   array_position(array[5,4,3,2,1],id) as ord 
from stuff where value=any(array[5,4,3,2,1]) 
order by ord;

输出:

 id | value | ord
----+-------+-----
  5 |     5 |   1
  4 |     4 |   2
  3 |     3 |   3
  2 |     2 |   4
  1 |     1 |   5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多