postgresql - 为什么 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",
}
]
解决方案
您是否在聚合中尝试了 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;
推荐阅读
- sql - 使用 Job schedule 将当前日期和时间输入到列中
- mysql - MySQL查询:获取通常有效地一起使用的项目的多对多关系的行
- bluetooth-lowenergy - BLE CoC(L2CAP CoC)的吞吐量是多少?
- javascript - 如果特定单词之前存在字符加空格,则不匹配
- java - Spring/Tomcat:源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- jmeter - 无法使用正则表达式提取器在 jmeter 中提取编码的 PDF 数据?
- rancher - 如何调试带有正常消息“SIGTERM RECEIVED”的牧场主服务器关闭抛出?
- c++ - 带有指向基类的指针的删除运算符如何释放内存
- kubernetes - WSO2 EI 6.5 - 名称或服务未知 | DefaultAddressPicker [LOCAL] [wso2.ei.domain] [3.5.4] 集成商名称或服务未知
- android - 放置 PRODUCT_PACKAGES+=mytool 的好 AOSP Makefile 在哪里