簡體   English   中英

如何在Postgresql中將數組拆分成行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM