gpt4 book ai didi

sql - Postgres SQL 查询,将对关联数组中的字段进行分组

转载 作者:行者123 更新时间:2023-11-29 13:20:16 25 4
gpt4 key购买 nike

示例:我有表“tickets”

id, int
client_id, int
client_name, text

我需要的不是通常的 select ("SELECT id, client_id, client_name FROM tickets") 结果:

{
"id": 2,
"client": {
"id": 31,
"name": "Mark"
}
}

最佳答案

如果你喜欢为此使用 SQL,有 json_build_object function :

SELECT
json_build_object(
'id', id,
'client', json_build_object(
'id', client_id,
'name', client_name))
FROM
tickets;

例子:

#!/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])

输出:

({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}

关于sql - Postgres SQL 查询,将对关联数组中的字段进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43260376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com