提问人:UnInfamousAlec 提问时间:11/17/2023 最后编辑:UnInfamousAlec 更新时间:11/18/2023 访问量:60
Postgres的 |将数组行转换为整数行
Postgres | Convert Rows of Arrays to Rows of Integers
问:
我遇到了一个我似乎无法克服的障碍,因为我无法可视化数据。我对 Postgres 相当陌生(对 Snowflake 更有经验,但不再有权访问),但由于复杂性和插入,我无法可视化数据。
查看其他帖子,我能够得到的最接近的是以下内容(它只呈现一个空白响应,我相信它与 TWO 子查询有关,但否则会丢失):
表 ALPHA(空表)
CREATE TABLE ALPHA (
X_ID SERIAL PRIMARY KEY,
X_JSON JSON
);
表格 CHARLIE (填充表格)
CREATE TABLE CHARLIE (
Y_ID INT NOT NULL PRIMARY KEY,
NAME TEXT NOT NULL
);
INSERT INTO CHARLIE (Y_ID, NAME)
VALUES (1,'A'),(2,'B'),(3,'C'),(4,'D'),(5,'E'),(6,'F'),(7,'G'),(8,'H'),(9,'I'),(10,'J'),(11,'K'),(12,'L');
表 BRAVO (空中间桌)
CREATE TABLE BRAVO (
X_ID INT NOT NULL REFERENCES ALPHA (X_ID),
Y_ID INT NOT NULL REFERENCES CHARLIE (Y_ID)
);
查询:
WITH ONE AS (
INSERT INTO ALPHA (X_ID, X_JSON)
VALUES (1, '{"a": [4,5,6]}'),
(2, '{"a": [7,8,9]}'),
(3, '{"a": [10,11,12]}')
RETURNING X_ID, JSON_EXTRACT_PATH(X_JSON, 'a') AS Y_ID
), TWO AS (
SELECT ALPHA.X_ID,
(SELECT * FROM JSON_TO_RECORDSET(ONE.Y_ID -> 'rows') AS list(columns int)) AS Y_ID_A
FROM ALPHA
JOIN ONE ON ALPHA.X_ID = ONE.X_ID
)
INSERT INTO BRAVO (X_ID, Y_ID)
SELECT X_ID,
Y_ID_A
FROM TWO
RETURNING *
我需要输出的样子,以便我可以将其插入到表 BRAVO 中:
X_ID | Y_ID |
---|---|
1 | 4 |
1 | 5 |
1 | 6 |
2 | 7 |
2 | 8 |
2 | 9 |
3 | 10 |
3 | 11 |
3 | 12 |
答:
0赞
SelVazi
11/17/2023
#1
您可以使用 json_array_elements
将 JSON 数组扩展到一组行:
WITH ONE AS (
INSERT INTO ALPHA (X_ID, X_JSON)
VALUES (1, '{"a": [4,5,6]}'),
(2, '{"a": [7,8,9]}'),
(3, '{"a": [10,11,12]}')
RETURNING X_ID, X_JSON->'a' AS Y_ID_A
),
TWO AS (
SELECT o.X_ID, v.value::text::int AS Y_ID
FROM ONE o
CROSS JOIN LATERAL json_array_elements (o.Y_ID_A) v
)
INSERT INTO BRAVO (X_ID, Y_ID)
SELECT X_ID,
Y_ID
FROM TWO
评论
1赞
UnInfamousAlec
11/18/2023
感谢您的快速回复!我在指定要插入的表时出错(没有TABLE_A)。我已经纠正了这一点。查看 DBFiddle,您已经指定了 BRAVO。Y_ID是 JSON,其中它是 INT。
0赞
SelVazi
11/18/2023
你能检查我最近的编辑吗
0赞
UnInfamousAlec
11/18/2023
那行得通,谢谢!我更喜欢更干净的类型转换,但我可以解决这个问题。
0赞
SelVazi
11/18/2023
很高兴听到我能帮:)
评论