首页 > 解决方案 > 为什么 json_agg 函数中的列显示顺序比临时表的变化 - PostgreSQL

问题描述

我正在 PostgreSQL 函数\proc 中创建一个临时表。

CREATE TEMP TABLE tbl_temp_class(id SERIAL PRIMARY key, batch_id INT, class_id INT, class_name VARCHAR);

稍后我将使用动态 sql 动态地将列添加到该表中。l_column_counter在for 循环中递增,直到n

l_sql_query := CONCAT('ALTER TABLE tbl_temp_class ADD column ', 'col', '_', l_column_counter, ' varchar default('''');');
EXECUTE l_sql_query;

最后,我希望 tbl_temp_class 结果作为 json 数组。因此我在下面做。

select json_agg(ut)
  from (
select * 
  from tbl_temp_class
 order by id) ut;

我希望上述查询的结果是

[ 
 {
     "id":1,
     "batch_id":1,
     "class_id":1,
     "class_name":"Maths",
     "col_1":"",
     "col_2":"",
     "col_3":"",
     "col_4":"",
     "col_5":""
  },
  {
     "id":2,
     "batch_id":1,
     "class_id":2,
     "class_name":"History",
     "col_1":"",
     "col_2":"",
     "col_3":"",
     "col_4":"",
     "col_5":""
  }
]

但是,我得到的结果如下。列显示顺序被打乱。知道如何解决这个问题吗?这是因为 json 是从临时表中生成的吗?我需要最终 json 数组中的列显示顺序与临时表中的列显示顺序相同。

[ 
 {
     "id":1,
     "col_1":"",
     "col_2":"",
     "col_3":"",
     "col_4":"",
     "col_5":"",
     "class_id":1,
     "batch_id":1,
     "class_name":"Maths",
  },
  {
     "id":2,
     "col_1":"",
     "col_2":"",
     "col_3":"",
     "col_4":"",
     "col_5":"",
     "class_id":2,
     "batch_id":1,
     "class_name":"History",
  }
]

标签: postgresql

解决方案


您是否在聚合中尝试了 ORDER BY ?

SELECT json_agg(ut ORDER BY id) -- this where you want to use the ORDER BY
  FROM (
SELECT * 
  FROM tbl_temp_class
 ORDER BY id) ut;

推荐阅读