PostgreSQL获取带有项目的订单

时间:2018-10-11 13:30:37

标签: sql database postgresql

我在数据库中有以下表格,

订单:

    |order_id | 
----+---------+
  1 | 123-456 |
  2 | 123-455 | 
  3 | 123-454 |

订购商品:

    |order_id |description| 
----+---------+------------
  1 | 123-456 |  ABC
  2 | 123-456 |  DEF
  3 | 123-456 |  GHI
  4 | 123-455 |  ABC
  5 | 123-454 |  DEF
  6 | 123-453 |  GHI

我想做的是以下事情:

SELECT o.*, array_to_json(array_agg(i.*)) as items
FROM orders o
LEFT OUTER JOIN order_items i
ON i.order_id = o.order_id
group by o.order_id

我需要能够选择包含特定说明的商品的订单,而且还要保留订单中的所有其他商品。

因此,如果我执行以下操作;

SELECT o.*, array_to_json(array_agg(i.*)) as items
FROM orders o
LEFT OUTER JOIN order_items i
ON i.order_id = o.order_id
WHERE i.description LIKE '%ABC%'
group by o.order_id

我需要结果是

    |order_id |items| 
----+---------+------------
  1 | 123-456 |  [{"order_id":"123-456","description":"ABC"},{"order_id":"123-456","description":"DEF"},{"order_id":"123-456","description":"GHI"}]
  2 | 123-455 |  [{"order_id":"123-455","description":"ABC"}]

谢谢。

2 个答案:

答案 0 :(得分:1)

假设您现有的查询基本上可以正常运行,我进行了以下更改...

  • o.*o.order_id
  • WHERE <condition>HAVING SUM(<condition>) >= 1

这给

SELECT o.order_id, array_to_json(array_agg(i.*)) as items
FROM orders o
LEFT OUTER JOIN order_items i
ON i.order_id = o.order_id
GROUP BY o.order_id
HAVING SUM(CASE WHEN i.description LIKE '%ABC%' THEN 1 END) >= 1

答案 1 :(得分:0)

SELECT o.*, array_to_json(array_agg(i.*)) as items
FROM orders o
JOIN order_items i
ON i.order_id = o.order_id
WHERE o.order_id in(select oi.order_id from order_items oi where oi.description LIKE '%ABC%')
group by o.order_id