Postgres查询结果到json对象

时间:2018-04-07 23:49:40

标签: postgresql pagination aggregate-functions jsonb sql-limit

我的查询如下:

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;

这给我的结果如下:

Result

我想改为{"payload:"[payload1,payload2,payload3],"rowcount":n}

Postgres版 10.3 payload数据类型为jsonb

2 个答案:

答案 0 :(得分:4)

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的嘈杂方式,并返回结果的总行数。

您当前的查询,简化:

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;

如果您正在处理多个行,LIMIT / OFFSET的效果会降低。考虑更复杂的分页技术:

答案 1 :(得分:1)

使用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