【问题标题】:PSQL group row_to_jjson outputsPSQL 组 row_to_jjson 输出
【发布时间】:2020-11-10 17:53:41
【问题描述】:

我有一个函数可以连接三个不同的表。我试图从连接中返回所有行,但根据它们的原始表将它们分组到不同的对象中。然后我想在此调用 psql 的 row_to_json 函数。

我的函数看起来像这样:

select format($q$
        select results
        from (
            select json_agg(row_to_json(s)) as results from (
                select g.* as all_g,o.* as all_o,d.* as all_d from schema.table_1 g
                join schema.table_2 o on g.eid = o.ev_id
                join schema.table_3 d on g.eid = d.id
                where g.eid = any(%1$L)
                ) s
        ) m;
    $q$,
        evs
    ) into q;

    return query execute q;

想要的输出是这样的:

[
 {
  "all_g": {
    "eid": 1,
    "name": "testing"
   },
  "all_o": {
   "ev_id": 25,
   "type": "type_name"
   },
  "all_d": {
   "id": 6
   }
  },
 {
  "all_g": {
    "eid": 2,
    "name": "testing_again"
   },
  "all_o": {
   "ev_id": 14,
   "type": "type_name_2"
   },
  "all_d": {
   "id": 75
   }
  }
]

当我运行我的代码时,g.* as all_g 没有按预期工作。有可能做我想要的吗?要将每个表中的结果嵌入到外部对象中?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    我可以通过如下改变结构来解决这个问题:

    select format($q$
            select results
            from (
                select json_agg(row_to_json(s)) as results from (
                    select row_to_json(g.*) as all_g,row_to_json(o.*) as all_o,row_to_json(d.*) as all_d from schema.table_1 g
                    join schema.table_2 o on g.eid = o.ev_id
                    join schema.table_3 d on g.eid = d.id
                    where g.eid = any(%1$L)
                    ) s
            ) m;
        $q$,
            evs
        ) into q;
    
        return query execute q;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-01
      • 2012-03-25
      • 2018-11-18
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多