【问题标题】:POSTGRESQL - unnested ARRAY values not behaving as expectedPOSTGRESQL - 未嵌套的 ARRAY 值未按预期运行
【发布时间】:2014-12-18 19:28:11
【问题描述】:

我需要取消嵌套这个数组,这样我就可以用一个 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'

然后我想加入下面的专业表,带入相应的专业文本。但是,我似乎对单引号 ' 包裹在它们周围的未嵌套值有问题。

我试过 trim 和 ltrim

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 我尝试将数组转换为整数,没有运气

投射尝试:

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

【问题讨论】:

  • 能否在 sqlfiddle.com 上提供一个简短的演示,以便我们查看原始数据?
  • 您使用了textvarchar 的数组,即text[],而不是整数数组integer[]
  • @CraigRinger 所以你建议这些数据一开始就存储不当,考虑到它们应该是整数 ID 号(这是它们从哪里添加到数组中)我想我是希望有一种简单的方法可以将其取消嵌套为数字,即使它被错误地存储为文本
  • @hackg 有:unnest(mycolumn::integer[])。但最好修复架构。我只是猜测这就是问题所在......你应该显示你的表定义,否则我所能做的就是猜测。

标签: arrays postgresql join


【解决方案1】:

这行得通 - 感谢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多