如何在Postgres中使用数组作为变量?

时间:2017-05-30 21:43:25

标签: postgresql postgresql-9.6

我有这个.sql脚本:

DO $$
  DECLARE 
    user_list integer[] = (select user_id from user where state = 'ACTIVE');
BEGIN
    CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    select * from accounts where user_account IN (user_list);
    ...

    CREATE CREATE MATERIALIZED VIEW accounts_without_active_users AS
    select * from accounts where user_account NOT IN (user_list);
    ...
END $$;

但是我总是有这个错误:

ERROR: cannot cast type integer to integer[]

我之前尝试使用array这个词,结果相同:

user_list integer[] = array(...)

1 个答案:

答案 0 :(得分:3)

您正在尝试将行集分配给数组。您可以改为使用array_agg()

user_list integer[] = (select array_agg(user_id) from users where state = 'ACTIVE');

据说这个恕我直言并没有真正帮助你创建物化视图。只需内联您的选择

即可
CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    SELECT * FROM accounts WHERE user_account IN (
        SELECT user_id FROM users WHERE state = 'ACTIVE'
    );

或创建active_users视图

CREATE VIEW active_users AS SELECT * FROM users WHERE state = 'ACTIVE';

并改为使用

CREATE CREATE MATERIALIZED VIEW accounts_with_active_users AS
    SELECT * FROM accounts WHERE user_account IN (
        SELECT user_id FROM active_users;
    );