相关疑难解决方法(0)

带有元素编号的PostgreSQL unnest()

当我有一个具有分隔值的列时,我可以使用该unnest()函数:

myTable
id | elements
---+------------
1  |ab,cd,efg,hi
2  |jk,lm,no,pq
3  |rstuv,wxyz

select id, unnest(string_to_array(elements, ',')) AS elem
from myTable

id | elem
---+-----
1  | ab
1  | cd
1  | efg
1  | hi
2  | jk
...
Run Code Online (Sandbox Code Playgroud)

我如何包含元素编号?即:

id | elem | nr
---+------+---
1  | ab   | 1
1  | cd   | 2
1  | efg  | 3
1  | hi   | 4
2  | jk   | 1
...
Run Code Online (Sandbox Code Playgroud)

我想要源字符串中每个元素的原始位置.我试着窗口函数(row_number(), …

sql arrays postgresql window-functions set-returning-functions

69
推荐指数
3
解决办法
8万
查看次数

表名作为PostgreSQL函数参数

我想在Postgres函数中传递一个表名作为参数.我试过这段代码:

CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer 
AS $$
    BEGIN
    IF EXISTS (select * from quote_ident($1) where quote_ident($1).id=1) THEN
     return 1;
    END IF;
    return 0;
    END;
$$ LANGUAGE plpgsql;

select some_f('table_name');
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

ERROR:  syntax error at or near "."
LINE 4: ...elect * from quote_ident($1) where quote_ident($1).id=1)...
                                                             ^

********** Error **********

ERROR: syntax error at or near "."
Run Code Online (Sandbox Code Playgroud)

以下是更改为此时出现的错误select * from quote_ident($1) tab where tab.id=1:

ERROR:  column tab.id does not exist
LINE 1: ...T EXISTS …
Run Code Online (Sandbox Code Playgroud)

postgresql function dynamic-sql plpgsql identifier

69
推荐指数
4
解决办法
7万
查看次数

在PostgreSQL中是否有类似两个数组的zip()函数?

我在PostgreSQL中有两个相同长度的数组值:

{a,b,c}{d,e,f}

我想把它们结合起来

{{a,d},{b,e},{c,f}}

有没有办法做到这一点?

sql arrays postgresql

21
推荐指数
2
解决办法
7298
查看次数

为什么PostgreSQL数组在C中的访问速度比在PL/pgSQL中快得多?

我有一个表模式,其中包含一个int数组列,以及一个自定义聚合函数,它对数组内容求和.换句话说,给出以下内容:

CREATE TABLE foo (stuff INT[]);

INSERT INTO foo VALUES ({ 1, 2, 3 });
INSERT INTO foo VALUES ({ 4, 5, 6 });
Run Code Online (Sandbox Code Playgroud)

我需要一个可以返回的"sum"函数{ 5, 7, 9 }.正确运行的PL/pgSQL版本如下:

CREATE OR REPLACE FUNCTION array_add(array1 int[], array2 int[]) RETURNS int[] AS $$
DECLARE
    result int[] := ARRAY[]::integer[];
    l int;
BEGIN
  ---
  --- First check if either input is NULL, and return the other if it is
  ---
  IF array1 IS NULL OR array1 = '{}' THEN
    RETURN array2;
  ELSEIF …
Run Code Online (Sandbox Code Playgroud)

c arrays postgresql plpgsql aggregate-functions

19
推荐指数
2
解决办法
3616
查看次数

更改视图中使用的PostgreSQL列

我希望PostegreSQL能够放松一下.每次我想要更改视图中使用的列时,似乎我必须删除视图,更改字段然后重新创建视图.我是否可以放弃额外的保护并告诉PostgreSQL让我更改字段然后找出对视图的调整?

澄清: 我理解一个观点是什么.事实上,这是因为视图就像一个子查询,我希望我可以更改基础表并让视图获取更改.

假设我有以下内容:

CREATE TABLE monkey
(
  "name" character varying(50) NOT NULL,
)

CREATE OR REPLACE VIEW monkey_names AS 
 SELECT name
   FROM monkey
Run Code Online (Sandbox Code Playgroud)

我真的只想在迁移脚本中执行以下操作,不必删除并重新创建视图.

ALTER TABLE monkey ALTER COLUMN "name" character varying(100) NOT NULL
Run Code Online (Sandbox Code Playgroud)

sql postgresql varchar types sql-view

6
推荐指数
1
解决办法
1万
查看次数