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

时间:2019-03-04 05:25:35

标签: sql json postgresql 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

给出了类似的架构和数据:

小车:

id  cart_total shopper_id
1   39         34
2   20         45

line_items:

id  cart_id    item_name item_price
1   1          egg       39
2   2          biscut     5
3   2          apple     15

付款:

id  cart_id payment_id
1   1       AS34gsdVSWET4
2   2       JFHERHJE$Y#$H

如何获取所有购物车列表以及特定shopperId的购物车列表?

2 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分:0)

SELECT c.id AS cart_id,
       c.cart_total,
       c.shopper_id,
       json_agg(
          json_build_object(i.item_name, 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;