我正在使用 PostgreSQL 9.5
我有兩張桌子:
一個
ID | isStatusA | IsStatusB | IsStatusC
0 | true | false | true
一個表只有 1 行我需要的資料。我也有B表:
ID | status | a_id
0 | A | 0
0 | C | 0
當我用“from A inner join B on a.id = b.a_id”撰寫我的選擇時,我得到了 2 行。我只需要得到一行(或 json 物件),并檢查表 A 中的真/假和表 B 中存在的狀態。要回傳真,我必須檢查這兩個條件。
我想要{A: true, B: false, C:true}或類似的東西使用樞軸。
uj5u.com熱心網友回復:
使用 PostgreSQLARRAY_AGG()函式以及GROUP BY“非規范化”B表status列。然后使用一個臨時的臨時表,這里命名INNER JOIN為.AB_agg
SELECT A.*, B_agg.status_agg
FROM A
INNER JOIN (
SELECT a_id, ARRAY_AGG(status) status_agg FROM B GROUP BY a_id
) B_agg ON A.ID = B_agg.a_id
;
輸出:
| ID | 狀態 | isstatusb | isstatusc | status_agg |
|---|---|---|---|---|
| 0 | 噸 | 噸 | F | {A,C} |
臨時表查詢:
SELECT a_id, ARRAY_AGG(status) status_agg FROM B GROUP BY a_id
...輸出:
| 援助 | status_agg |
|---|---|
| 0 | {A,C} |
然后,此結果INNER JOIN與表A連接列A.ID和B_agg.a_id:一起使用ON A.ID = B_agg.a_id。
臨時表被賦予了在臨時表查詢之外訪問的別名B_agg,例如:B_agg.status_agg.
在這里試試:https ://onecompiler.com/postgresql/3yfyffrrg
歸功于:https ://stackoverflow.com/a/6558226/2743458
uj5u.com熱心網友回復:
使用JSON_AGG()andJSON_BUILD_OBJECT()創建 JSON 物件并分配所需的物件鍵名:
SELECT JSON_AGG(
JSON_BUILD_OBJECT('A',isStatusA,'B',isStatusB,'C',isStatusB)
) status_agg
FROM A
;
輸出:
| status_agg |
|---|
| [{“A”:真,“B”:真,“C”:真}] |
在這里試試:https ://onecompiler.com/postgresql/3yfyjt24r
該A表提供了生成輸出所需的所有資訊{A: true, B: false, C:true}。
ID如果在單個查詢中收集多個 ID,還可以包括該列:
SELECT JSON_AGG(
JSON_BUILD_OBJECT(ID,
JSON_BUILD_OBJECT('A',isStatusA,'B',isStatusB,'C',isStatusB)
)
) status_agg
FROM A
;
輸出:
| status_agg |
|---|
| [{“0”:{“A”:真,“B”:真,“C”:真}}] |
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510822.html
