【问题标题】:Postgres SQL query, that will group fields in associative arrayPostgres SQL 查询,它将对关联数组中的字段进行分组
【发布时间】:2017-09-01 18:58:45
【问题描述】:

示例:我有桌子“票”

id, int
client_id, int
client_name, text

而不是通常的选择 ("SELECT id, client_id, client_name FROM Tickets") 我需要一些可以作为结果的东西:

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

【问题讨论】:

    标签: sql arrays json postgresql psycopg2


    【解决方案1】:

    如果你喜欢用 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}

    【讨论】:

    • 它可以工作,但每个结果都是“json_build_object”。看起来像:{ "json_build_object": {id: ...} },{ "json_build_object": {id: ...} }。我可以提高数据级别吗?
    • 没有"json_build_object"
    • @IldarAkhmetzyanov 可能我们在代码上有一些差异。添加示例。
    • 设置问题:cursor_factory=RealDictCursor.
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2013-07-06
    • 1970-01-01
    相关资源
    最近更新 更多