假設我有以下兩個表:
-- table_1
| id | name |
| 1000 | name1 |
| 1001 | name2 |
| 1002 | name3 |
| 1003 | name4 |
-- table_2
_______________________________
| id | table_1_fk_list |
| 101 | [1003] |
我的查詢回傳以下內容:
[
{
"id": "101",
"table_1_elements_list": [ "1003" ],
},
]
但我想回傳這個:
[
{
"id": "101",
"table1ElementsList": [
{
"id": "1003",
"name": "name4"
}
],
},
]
是否有可能做到這一點?這是我的查詢:
SELECT
id,
table_1_fk_list as "table1ElementsList"
FROM table_2
我試過像這樣加入這兩個表,但沒有用:
SELECT
id,
table_1_fk as "table1ElementsList"
FROM table_2 t2
JOIN table_1 t1
ON (t1.id = ANY(t2.table_1_fk_list))
使用 MongoDB,我可以使用$unwind聚合或只是一個簡單的方法populate,但我對 Postgres 有點陌生。
uj5u.com熱心網友回復:
您在預期的 json 結果中有兩個級別的聚合。嘗試這樣的事情:
SELECT jsonb_agg(jsonb_build_object('id', t2.id, 'table1ElementsList', t3.json_data)
FROM table_2 AS t2
CROSS JOIN LATERAL
( SELECT jsonb_agg(jsonb_build_object('id', t1.id, 'name', t1.name)) AS json_data
FROM unnest(t2.table_1_fk_list) AS fkl(id)
INNER JOIN table_1 AS t1
ON t1.id = fkl.id
) AS t3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366096.html
標籤:PostgreSQL的
