POSTGRESQL - unnested ARRAY值不符合预期

时间:2014-12-18 19:28:11

标签: arrays postgresql join

我需要取消此数组,以便我可以使用ID列表(整数)加入

CREATE TABLE studies  
( 
 study_id INTEGER,
 specialties TEXT[]
)
 WITH (
  OIDS=FALSE
);


CREATE TABLE specialties
(
specialty_id INTEGER,
specialty_text TEXT[]
)
 WITH (
  OIDS=FALSE
);

研究数据

study_id    specialties 
2333    {}
2332    {}
2329    {'1635','1646'}     
2328    {}
2327    {'1643','1695','1696'}  

专业数据

specialty_id    specialty_text
1635        Nephrology
1643        General Surgery
1646        Nephrology
1692        Internal Medicine
1695        Neurology

使用此查询

可以正常运行数组
select study_id, unnest(specialties) as spec_id
from studies
where study_id in (2333,2332,2330,2329)

结果

study_id        spec_id
2329        '1635'
2329        '1646'
2327        '1643'
2327        '1695'
2327        '1696'

我想加入以下专业表,带来相应的专业文字。然而,我似乎遇到了包含单引号的unnested值的问题。

我试过修剪和修剪

select study_id, trim(both '''' from unnest(specialties)) as spec_id
from studies
where study_id in (2333,2332,2330,2329,2328,2327,2318,2317)

但结果仍然看起来完全相同,单引号未被删除 - 任何删除这些的想法,所以我可以转换为整数或加入数字字段?

study_id        spec_id
2329        '1635'
2329        '1646'
2329        '850761'
2329        '877725'
2329        '1664'

更新

添加了表定义和@CraigRinger我尝试将数组转换为整数,没有运气

CAST ATTEMPT:

select study_id, unnest(specialties::integer) as spec_id
from studies
where study_id in (2333,2332,2330,2329,2328,2327,2318,2317)

结果:

ERROR: cannot cast type text[] to integer
SQL state: 42846

1 个答案:

答案 0 :(得分:0)

这很有用 - 感谢@pozs指出我的修剪是不正确的,修复它让我可以正确地转换为整数

select study_id, trim(both '''' from unnest(specialties))::integer as spec_id
from studies
where study_id in (2333,2332,2330,2329,2328,2327,2318,2317)

结果

    study_id       spec_id  
   (integer)      (integer)  
    2329           1635
    2329           1646
    2327           1696
    2327           1643
    2327           1695