在postgresql中使用where条件与数组不起作用

baubqpgj  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(157)

我试图使用一个数组,它是在postgres脚本中声明的,但我一直得到以下错误:

op ANY/ALL (array) requires array on right side

字符串
下面是我的代码:

DO $$ 
DECLARE
   id_cie VARCHAR(50) := ARRAY(select id from main_cies);
BEGIN
   RAISE NOTICE '%%%', id_cie;
   drop table if exists network;
   create table network as
   select
       req_real_estate_qc_shareholders.id as id,
       req_real_estate_qc_shareholders.name as name,
       'Main owners' as relation,
       req_real_estate_qc_shareholders.address_num as num,
       req_real_estate_qc_shareholders.street_name as street,
       req_real_estate_qc_shareholders.suite as suite,
       req_real_estate_qc_shareholders.zip as zip
   from req_real_estate_qc_shareholders 
   where req_real_estate_qc_shareholders.id = ANY(id_cie);
END $$;


我不理解这个错误,因为当我打印值时,我得到了以下数组:

{1173569659,1173569659}

ulydmbyx

ulydmbyx1#

id_cie VARCHAR(50) := ARRAY(select id from main_cies);将数组转换为字符串('{1173569659,1173569659}')。
如:

select pg_typeof(array[1,2]::varchar);
     pg_typeof     
-------------------
 character varying

字符串
您正在寻找VARCHAR[]

select pg_typeof(array[1,2]::varchar[]);
      pg_typeof      
---------------------
 character varying[]


于是:
id_cie VARCHAR[] := ARRAY(select id from main_cies);
但是如果id s实际上是整数,我会选择:
id_cie INTEGER[] := ARRAY(select id from main_cies);

mm5n2pyu

mm5n2pyu2#

你可以在不使用变量的情况下编写同样的功能。这避免了变量声明错误的问题:它不是数组。
这可能行得通:

DO
$$
    BEGIN
        DROP TABLE IF EXISTS network;
        CREATE TABLE network AS
        SELECT req_real_estate_qc_shareholders.id          AS id
             , req_real_estate_qc_shareholders.name        AS name
             , 'Main owners'                               AS relation
             , req_real_estate_qc_shareholders.address_num AS num
             , req_real_estate_qc_shareholders.street_name AS street
             , req_real_estate_qc_shareholders.suite       AS suite
             , req_real_estate_qc_shareholders.zip         AS zip
        FROM req_real_estate_qc_shareholders
                 JOIN main_cies ON req_real_estate_qc_shareholders.id = main_cies.id;
    END
$$;

字符串

相关问题