运行此查询时:
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。
非常感谢!
答案 0 :(得分:5)
我建议你升级你的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;