我在 postgres 数据库中有这样的东西:
| foo | 1,2 | a,b |
我想把它扩展到:
| foo | 1 | a |
| foo | 2 | b |
我知道我可以用 plpgsql 做到这一点,但想知道是否有办法用 sql 来做到这一点。
提前致谢
最佳答案
考虑这个演示:
SELECT name
,unnest(a)
,unnest(b)
FROM (VALUES ('foo', '{1,2}'::int[], '{a,b}'::text[])) t(name, a, b)
结果:
name | unnest | unnest
------+--------+--------
foo | 1 | a
foo | 2 | b
(2 rows)
或者,如果您有逗号分隔的字符串而不是 ARRAY:
SELECT name
,regexp_split_to_table(a, ',')
,regexp_split_to_table(b, ',')
FROM (VALUES ('foo', '1,2'::text, 'a,b'::text)) t(name, a, b)
相同的结果。
更多关于 unnest()
和 regexp_split_to_table()
在手册中。
关于sql - 为包含列表的单元格返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8491427/