gpt4 book ai didi

sql - 自定义 jsonb 键排序顺序

转载 作者:行者123 更新时间:2023-11-29 12:25:50 27 4
gpt4 key购买 nike

我在 PostgreSQL 中有一个表,其中包含一些数据:

create table t2 (
key jsonb,
value jsonb
);

insert into t2(key, value) values ('1', '"test 1"');
insert into t2(key, value) values ('2', '"test 2"');
insert into t2(key, value) values ('3', '"test 3"');
insert into t2(key, value) values ('[]', '"test 4"');
insert into t2(key, value) values ('[1]', '"test 5"');
insert into t2(key, value) values ('[2]', '"test 6"');
insert into t2(key, value) values ('[3]', '"test 7"');
insert into t2(key, value) values ('[1, 2]', '"test 8"');
insert into t2(key, value) values ('[1, 2, 3]', '"test 9"');
insert into t2(key, value) values ('[1, 3]', '"test 10"');
insert into t2(key, value) values ('[1,2,4]', '"test 11"');
insert into t2(key, value) values ('[1, 2,4]', '"test 12"');
insert into t2(key, value) values ('[1,3,13]', '"test 13"');
insert into t2(key, value) values ('[1, 2, 15]', '"test 15"');

然后我尝试对这些行进行排序:

SELECT key FROM t2 order by key;

结果是:

[]
1
2
3
[1]
[2] <==
[3] <==
[1, 2]
[1, 3] <==
[1, 2, 3]
[1, 2, 4]
[1, 2, 4]
[1, 2, 15]
[1, 3, 13]

但是我需要的是

[]
1
2
3
[1]
[1, 2]
[1, 2, 3]
[1, 2, 4]
[1, 2, 4]
[1, 2, 15]
[1, 3] <==
[1, 3, 13]
[2] <==
[3] <==

有什么办法可以实现吗?

最佳答案

混合类型会有些痛苦,你可能并不意味着只有三个值 :) 但仍然是一个想法:

SELECT key FROM t2 order by (key->>0)::text::int,(key->>1)::int ,(key->>2)::int;

将给予:
“[1, 2, 3]”
“[1, 2, 4]”
“[1, 2, 4]”
“[1, 2, 15]”
“[1, 2]”
“[1, 3, 13]”
“[1, 3]”
“1”
“[1]”
“2”
“[2]”
“3”
“[3]”
“[]”

关于sql - 自定义 jsonb 键排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998765/

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