Postgresql查询,它将对关联数组中的字段进行分组

Postgres SQL query, that will group fields in associative array

示例:我有一张桌子"门票"

1
2
3
id, INT
client_id, INT
client_name, text

与通常的选择(" SELECT id,client_id,client_name FROM票证")不同,我需要一些可以提供的结果:

1
2
3
4
5
6
7
{
   "id": 2,
   "client": {
       "id": 31,
       "name":"Mark"
    }
}

如果您想为此使用SQL,则可以使用json_build_object函数:

1
2
3
4
5
6
7
8
SELECT
  json_build_object(
    'id', id,
    'client', json_build_object(
      'id', client_id,
      'name', client_name))
FROM
  tickets;

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python

import psycopg2
import json

conn = psycopg2.connect('')
cur = conn.cursor()
cur.execute("""
    with tickets(id, client_id, client_name) as (values(1,2,'x'),(3,4,'y'))
    SELECT
      json_build_object(
        'id', id,
        'client', json_build_object(
          'id', client_id,
          'name', client_name))
    FROM
      tickets;
   "
"")

FOR ROW IN cur.fetchall():
    print ROW, json.dumps(ROW[0])

输出:

1
2
({u'client': {u'id': 2, u'name': u'x'}, u'id': 1},) {"client": {"id": 2,"name":"x"},"id": 1}
({u'client': {u'id': 4, u'name': u'y'}, u'id': 3},) {"client": {"id": 4,"name":"y"},"id": 3}