在Postgres中将逗号分隔的字符串转换为整数数组

问题描述 投票:4回答:2

我试图将逗号分隔的字符串转换为整数数组(integer [])以在Where子句中使用。

我试过演员,::Int哪个不行。感谢您的意见

Table A   |  Table B
ID        |  Set_id
2         |  14,16,17
1         |  15,19,20
3         |  21

我的查询:

Select * 
from Table a, table b 
where a.id in b.set_id
sql postgresql
2个回答
17
投票

如果要将其用于连接条件,则需要将字符串转换为正确的整数数组。

Select * 
from Table a
  join table b on a.id = any(string_to_array(b.set_id, ',')::int[]);

但更好的解决方案是正确规范化表(或者至少将这些ID存储在整数数组中,而不是varchar列)


2
投票
Select * from Table_a a, table_b  b
where a.id = any(regexp_split_to_array(b.set_id,',')::int[]);
© www.soinside.com 2019 - 2024. All rights reserved.