【问题标题】:Aggregating table to json combined with references to other tables将表聚合到 json 并结合对其他表的引用
【发布时间】:2023-01-19 21:32:20
【问题描述】:

表一:

id status
1 1
2 4

表 B:

id status a_id
1 1 1
2 3 1
3 5 2
Table A (
id int,
status int);

Table B(
id int,
status int,
a_id int foreignt key reference A
);

当我在 (1,3) 中寻找状态时,如何进行返回此类输出的查询?

id status arrayjson
1 1 [{id=1,status=1,a_id=1},{id=2,status=3,a_id=1}]

如果我在 ( 3 ) 中寻找状态,它应该返回:

id status arrayjson
1 1 [{id=2,status=3,a_id=1}]

如果我在 ( 4 ) 中寻找状态,它应该返回:

id status arrayjson
2 4 []

如果我在 ( 5 ) 中寻找状态,它应该返回:

id status arrayjson
2 4 [{id=2,status=4,a_id=2}]

【问题讨论】:

  • 你的例子表明 status 是从表 b 中选择的。 status = 4 的情况不一致,因为这里的状态似乎是从表 a 中获取的 - 我希望这里没有行或来自 a 的所有行都以空数组作为输出 - 请澄清。

标签: sql json postgresql aggregation


【解决方案1】:

鉴于您的一组搜索状态值,您可以使用:

  • GENERATE_SERIES,生成您可能的 seek_status 值
  • JSON_BUILD_OBJECT,从你的 B 表开始构建你的 json
  • JSON_AGG,聚合你的 json
  • WHERE v.seek_status IN (1,3),更改你需要的seek_status
  • ORDER BY A.status DESC LIMIT 1,获取所有输出记录中可能的最高状态
SELECT A.*,
       CASE WHEN B.status IS NOT NULL
            THEN JSON_AGG(JSON_BUILD_OBJECT('id'    , B.id,
                                            'status', B.status,
                                            'a_id'  , B.a_id   ))
            ELSE '[]' END AS arrayjson
FROM      GENERATE_SERIES(1,5) v(seek_status)
LEFT JOIN B ON v.seek_status = B.status
LEFT JOIN A ON v.seek_status >= A.status
WHERE v.seek_status IN (1,3)
GROUP BY A.id, A.status, B.status
ORDER BY A.status DESC
LIMIT 1

查看演示 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2011-01-16
    • 2014-01-25
    相关资源
    最近更新 更多