sql - 如何在SQL中将字符串转换为数组

标签 sql postgresql sql-function

在一列中我有“1;2;3;6-9”

我需要将此字符串放入像这样的数组中(1,2,3,6,7,8,9)

select range from my_table

返回

| range     |
|-----------| 
| 1;2;3;6-9 |

我需要运行

select id from my_another_table where id in("1;2;3;6-9")
| id |
|----| 
| 1  |
| 2  |
| 3  |
| 6  |
| 7  |
| 8  |
| 9  |

最佳答案

这是一个糟糕的数据结构。但是您可以使用 generate_series() 和字符串函数来做到这一点:

select generate_series(v2.lo, v2.hi, 1)
from (values ('1;2;3;6-9')) v(str) cross join lateral
     regexp_split_to_table(v.str, ';') as r(range) cross join lateral
     (values (case when range not like '%-%' then range::int else split_part(range, '-', 1)::int end,
              case when range not like '%-%' then range::int else split_part(range, '-', 2)::int end
             )
     ) v2(lo, hi);

关于sql - 如何在SQL中将字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601410/

相关文章:

sql - 在 SQL 中对重复的行进行分组

java - Hibernate native 查询显示异常

java - 通过与旧值进行比较来拦截 DB 中的字段是否已使用 JAVA 更改

SQL Server : How to execute UPDATE from within recursive function?

sql-server - @@FETCH_STATUS <>-1 和 @@FETCH_STATUS <>-2 是什么意思?

mysql - Mysql中不同表的两列中的两个集合的交集

mysql - 如果 MySQL 查询中存在则加入

sql - Postgresql 函数波动性类别

node.js - 如何动态更改查询的值

Django .order_by() 与 .distinct() 使用 postgres