联接表,其中JSON字段ID对应于其他表中的列

时间:2019-05-05 10:12:37

标签: json postgresql

我有两个表,第一个表称为orders,它存储一个类似于以下内容的json []数据类型:

CREATE TABLE orders (id SERIAL, items: json[], price: REAL);

INSERT INTO orders (items, price) VALUES ('[{"itemId":1,"addons":["ice","cream"]},{"itemId":2,"addons":["mayo","peppers"]}]',12.4);

另一个称为项的项,将与“ itemId”相对应的itemId存储在json数据类型中:

CREATE TABLE items(id SERIAL, name TEXT, price REAL);

INSERT INTO items(name,price) VALUES ('Chicken Bowl', 8.99);

我想以这样的方式联接表,以便从项目表中返回与订单表中的itemId对应的文本值,而不是id本身,例如,为“ itemId”返回“ Chicken Bowl”大于1

1 个答案:

答案 0 :(得分:0)

尽管架构对于这种类型的查询而言并不是很好,但是这是一种实现方式:

SELECT o.id, i.name
FROM orders AS o
    LEFT JOIN LATERAL unnest(o.items) AS u ON (true)
    INNER JOIN items AS i ON ((u->>'itemId')::int = i.id)
;

...产生(根据给定的测试数据):

 id |     name     
----+--------------
  1 | Chicken Bowl
(1 row)

如果要将所有项目汇总到每个订单,请使用以下命令:

SELECT o.id AS order, array_agg(i.name) AS items
FROM orders AS o
    LEFT JOIN LATERAL unnest(o.items) AS u ON (true)
    INNER JOIN items AS i ON ((u->>'itemId')::int = i.id)
GROUP BY 1;

...生产中:

 order |      items       
-------+------------------
     1 | {"Chicken Bowl"}
(1 row)