Postgres 查询结果到 json 对象

Postgres query result to json object

我的查询如下

SELECT w.payload,
       Count('payload') OVER () AS ROWCOUNT
FROM wholesale_confirmation.wholesale_order_confirmation w
WHERE w.delivery_date = COALESCE(NULL, w.delivery_date)
  AND w.ship_to_location_id = COALESCE(NULL, w.ship_to_location_id)
  AND w.order_raised_date = COALESCE(NULL, w.order_raised_date)
  AND w.ship_from_location_id = COALESCE(NULL, w.ship_from_location_id)
LIMIT 10
OFFSET 0;

给我这样的结果:

我想要 {"payload:"[payload1,payload2,payload3],"rowcount":n}.


Postgres版本10.3payload数据类型为jsonb

使用json_build_object:

WITH foobar AS ( 
SELECT w.payload,
       Count('payload') OVER () AS ROWCOUNT
FROM wholesale_confirmation.wholesale_order_confirmation w
WHERE w.delivery_date = COALESCE(NULL, w.delivery_date)
  AND w.ship_to_location_id = COALESCE(NULL, w.ship_to_location_id)
  AND w.order_raised_date = COALESCE(NULL, w.order_raised_date)
  AND w.ship_from_location_id = COALESCE(NULL, w.ship_from_location_id)
LIMIT 10
OFFSET 0
)

SELECT 
    json_build_object('payload', payload, 'rowcount', rowcount)
FROM 
    foobar 

COALESCE(NULL, w.delivery_date) 归结为 w.delivery_date.

因此 WHERE w.delivery_date = COALESCE(NULL, w.delivery_date) 归结为 WHERE w.delivery_date IS NOT NULL

Count('payload') OVER () AS ROWCOUNT 只是表达 count(*) OVER () AS rowcount 和 returns 结果总行数的一种嘈杂方式。

您当前的查询,已简化:

SELECT payload, count(*) OVER () AS rowcount
FROM   wholesale_confirmation.wholesale_order_confirmation
WHERE  delivery_date          IS NOT NULL
AND    ship_to_location_id    IS NOT NULL
AND    order_raised_date      IS NOT NULL
AND    ship_from_location_id  IS NOT NULL
LIMIT  10;

要像更新后的问题一样获得一个 JSON 对象,其中包含一个 JSON 对象数组和总行数:

SELECT json_build_object('payload', jsonb_agg(payload), 'rowcount', min(rowcount))
FROM  (
   SELECT payload, count(*) OVER () AS rowcount
   FROM   wholesale_confirmation.wholesale_order_confirmation
   WHERE  delivery_date          IS NOT NULL
   AND    ship_to_location_id    IS NOT NULL
   AND    order_raised_date      IS NOT NULL
   AND    ship_from_location_id  IS NOT NULL
   LIMIT  10
   ) sub;
  • Best way to get result count before LIMIT was applied

如果您正在处理 行,LIMIT / OFFSET 的性能会下降。考虑一种更复杂的分页技术: