sql - 如何使用 postgress sql 获取数组子查询?
问题描述
所以,我需要的是下面的 json。
var plan = [{
id: 11,
title: 'give a title',
actions: [
{id: 1,
planId: 11,
title: 'give action name'},
{
id: 3,
planId: 11,
title: 'give another action name'
}
]},
{
id: 13,
title: 'thirteen a title',
actions: [
{id: 1,
planId: 13,
title: 'thirteen action name'},
{
id: 3,
planId: 13,
title: 'thirteen another action name'
}
]}
]
所以我有 2 张桌子、计划和行动。两个表之间的关系是计划有很多动作。计划(ID,标题)动作(ID,标题,计划ID)
SELECT
*,
ARRAY (
SELECT
jsonb_build_object ('id',
m.id,
'title',
m.title)
FROM
actions a
INNER JOIN plan p ON p.id = a.planid
) AS actions
FROM
plan
我不确定如何获得每个计划下的相关操作。
解决方案
这些查询可能是您要查找的内容:
数据样本
CREATE TEMPORARY TABLE plan (id INT, title TEXT);
CREATE TEMPORARY TABLE action (id INT, title TEXT, planid INT);
INSERT INTO plan VALUES (1,'plan a'),(2,'plan b');
INSERT INTO action VALUES (1,'1st action plan a',1),
(2,'2nd action plan a',1),
(3,'1st action plan b',2);
查询 - 多条 json 记录
SELECT
json_build_object(
'id',p.id,'title',p.title,
'actions',(SELECT json_agg(row_to_json(t))
FROM (SELECT id,title,planid
FROM action WHERE planid = p.id) t)) AS myjson
FROM plan p;
myjson
------------------------------------------------------------------------------------------------------------------------------------------------
{"id" : 1, "title" : "plan a", "actions" : [{"id":1,"title":"1st action plan a","planid":1}, {"id":2,"title":"2nd action plan a","planid":1}]}
{"id" : 2, "title" : "plan b", "actions" : [{"id":3,"title":"1st action plan b","planid":2}]}
(2 Zeilen)
查询 - 单个 json 记录
SELECT json_agg(row_to_json(myjson)) FROM
(SELECT
json_build_object(
'id',p.id,'title',p.title,
'actions',(SELECT json_agg(row_to_json(t))
FROM (SELECT id,title,planid
FROM action WHERE planid = p.id) t)) as plan
FROM plan p) myjson;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[{"plan":{"id" : 1, "title" : "plan a", "actions" : [{"id":1,"title":"1st action plan a","planid":1}, {"id":2,"title":"2nd action plan a","planid":1}]}}, {"plan":{"id" : 2, "title" : "plan b", "actions" : [{"id":3,"title":"1st action plan b","planid":2}]}}]
(1 Zeile)
推荐阅读
- php - Laravel 迁移错误:找不到基表或视图
- python - 如何使用按钮浏览下一个和上一个列表项?
- java - 给定数组表示 S 所需的最小数字计数
- python - Filter grouped pandas dataframe, keep all rows with minimum value in column
- javascript - 赛普拉斯:对意外访问/请求错误进行故障排除
- python - ValueError:形状 (None, 1) 和 (None, 101) 不兼容
- css - 名称修改导致选择器不选择
- javascript - 如何打开一个新的空白窗口并使新的空白窗口在 Javascript 中显示警报?
- r - 如何在所有组合中使用 SD 求平均值
- angular - Angular Service Worker 在预取资产时是否会阻止其他网络请求?