与PostgreSQL有一对多关系的SQL查询

Udh*_*aya 0 sql postgresql json aggregate

我正在尝试通过与line_items表相关的查询来汇总购物车商品列表。我已经提取了一个用例的简单示例:

我的预期结果将如下所示:

cart_id  cart_total shopper_id items                                                        payment_id
      1         345         34 [{"name":"egg","price:"39"}]                                 AS34gsdVSWET4
      2          54         45 [{"name":"biscut","price:"5"},{"name":"apple","price:"15"}]  JFHERHJE$Y#$H
Run Code Online (Sandbox Code Playgroud)

给定一个模式和数据,例如:

推车:

id  cart_total shopper_id
1   39         34
2   20         45
Run Code Online (Sandbox Code Playgroud)

line_items:

id  cart_id    item_name item_price
1   1          egg       39
2   2          biscut     5
3   2          apple     15
Run Code Online (Sandbox Code Playgroud)

付款:

id  cart_id payment_id
1   1       AS34gsdVSWET4
2   2       JFHERHJE$Y#$H
Run Code Online (Sandbox Code Playgroud)

如何获取所有购物车列表并获取特定的购物车列表shopperId

Lau*_*lbe 5

这是我使用的解决方案json_build_object

SELECT c.id AS cart_id,
       c.cart_total,
       c.shopper_id,
       json_agg(
          json_build_object(
             'item_name', i.item_name,
             'item_price', i.item_price::text
          )
       ) AS items,
       p.payment_id
FROM carts AS c
   JOIN line_items AS i ON i.cart_id = c.id
   JOIN payment AS p ON p.cart_id = c.id
GROUP BY c.id, c.cart_total, c.shopper_id, p.payment_id;
Run Code Online (Sandbox Code Playgroud)

您确定要将价格作为字符串吗?