[英]How to split array into rows in Postgresql
运行此查询时:
SELECT id,selected_placements
FROM app_data.content_cards
我得到这样一张桌子:
+----+-------------------------------+
| id | selected_placements |
+----+-------------------------------+
| 90 | {162,108,156,80,163,155,NULL} |
+----+-------------------------------+
| 91 | {} |
+----+-------------------------------+
我现在要做的是得到相同的信息,但是将数组分成行,所以得到如下结果:
+----+---------------------+
| id | selected_placements |
+----+---------------------+
| 90 | 162 |
+----+---------------------+
| 90 | 108 |
+----+---------------------+
| 90 | 156 |
+----+---------------------+
| 90 | 80 |
+----+---------------------+
| 90 | 163 |
+----+---------------------+
| 90 | 155 |
+----+---------------------+
如您所见,我不想在“selected_placements”中获取具有空值的行。
我正在使用PostgreSQL 8.0.2。
非常感谢!
我建议你升级你的Postgres版本。 所有受支持的版本都支持unnest()
:
SELECT x.*
FROM (SELECT id, UNNEST(selected_placements) as selected_placement
FROM app_data.content_cards
) x
WHERE selected_placement IS NOT NULL;
在早期版本中,您可以尝试一次选择一个。 以下是测试和工作,虽然在9.5:
with content_cards as (
select 1 as id, array['a', 'b', 'c'] as selected_placements
)
SELECT id, selected_placements[num] as selected_placement
FROM (SELECT cc.*, generate_series(1, ccup.maxup) as num
FROM content_cards cc CROSS JOIN
(SELECT MAX(ARRAY_UPPER(cc.selected_placements, 1)) as maxup
FROM content_cards cc
) ccup
) x
WHERE selected_placements[num] IS NOT NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.