gpt4 book ai didi

sql - 如何在 Postgresql 中将数组拆分为行

转载 作者:行者123 更新时间:2023-11-29 11:39:27 38 4
gpt4 key购买 nike

运行此查询时:

  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/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com