运行此查询时:

  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;

关于sql - 如何在PostgreSQL中将数组拆分为行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43573001/

10-16 21:43