postgresql – Postgres查询结果到json对象
发布时间:2020-12-13 15:59:17 所属栏目:百科 来源:网络整理
导读:我的查询如下 SELECT w.payload,Count('payload') OVER () AS ROWCOUNTFROM wholesale_confirmation.wholesale_order_confirmation wWHERE w.delivery_date = COALESCE(NULL,w.delivery_date) AND w.ship_to_location_id = COALESCE(NULL,w.ship_to_location
我的查询如下
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.3,有效载荷数据类型是jsonb 解决方法
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; > Best way to get result count before LIMIT was applied 如果要处理许多行,LIMIT / OFFSET的性能会降低.考虑更复杂的分页技术: > Optimize query with OFFSET on large table (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |