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

sam*_*sam 8 sql arrays postgresql

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

我试过演员,::Int但没有奏效.感谢您的意见

Table A   |  Table B
ID        |  Set_id
2         |  14,16,17
1         |  15,19,20
3         |  21
Run Code Online (Sandbox Code Playgroud)

我的查询:

Select * 
from Table a, table b 
where a.id in b.set_id
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 20

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

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

很多更好的解决办法是正确正常化你的表(或者至少在一个整数数组存储这些ID,而不是一个varchar列)

  • 当某些原始数据在某些文件中存储为“1,23,456”时,可能会发生这种情况。您必须将它们转换为整数数组,以减少存储使用量并提高性能。 (2认同)

Kau*_*yak 6

Select * from Table_a a, table_b  b
where a.id = any(regexp_split_to_array(b.set_id,',')::int[]);
Run Code Online (Sandbox Code Playgroud)


Vic*_*Ray 6

您可以使用 unnest() 函数。unnest 函数用于将数组扩展为一组行。
Select * from Table_a a, table_b b where a.id in (SELECT unnest(string_to_array(b.set_id, ',')::int[]));