【问题标题】:Join records from another table as JSON array将另一个表中的记录连接为 JSON 数组
【发布时间】:2020-02-22 01:47:45
【问题描述】:

我们有两个表:“product”和“product_part”。 一个产品可以有多个产品部件,因此 product_part 具有引用产品的 id 列的 id_product 列。

我真的很想从这个数据集中创建一个MATERIALIZED VIEW:

| Product | Product Part|
+-----------------------+
| Gearbox | Metal scrap |
+-----------------------+
| Gearbox | Iron scrap  |
+-----------------------+
| Gearbox | Gold scrap  |
+-----------------------+

将创建此输出:

| Product | Parts                                          |
+---------+------------------------------------------------+
| Gearbox | ["Metal scrap", "Iron scrap", "Gold scrap"]    |
+---------+------------------------------------------------+

【问题讨论】:

    标签: sql json postgresql join


    【解决方案1】:

    这只是:

    SELECT product.name, json_agg(product_part.name) as parts
    FROM product
    JOIN product_part ON product.id = product_part.product_id
    GROUP BY product.id, product.name;
    

    我不得不猜测一下您的实际列,但这应该很接近。

    【讨论】:

    • 谢谢。我认为结合物化视图可以很好地使用它来优化应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多