我有一个在PostgreSQL中的表,其中包含一个存储JSON对象的列:
CREATE TABLE test (
rec_id int GENERATED BY DEFAULT AS IDENTITY,
usr_id int UNIQUE,
format text[],
syn_data jsonb,
generation_date timestamptz
);
INSERT INTO test VALUES
(2,
144,
'{audio,image,text}',
'{
"7458": {"syn_idx": [724966,125940,727242], "score": 5.0, "custom_score": 1.0},
"1742": {"syn_idx": [119294,119321], "score": 5.0, "custom_score": 1.0},
"38521": {"syn_idx": [654145], "score": 5.0, "custom_score": 1.0},
"4154": {"syn_idx": [617595,348300], "score": 5.0, "custom_score": 1.0}
}',
'2023-07-19 06:29:51.584859');
对于每行数据,syn_data
列中的键是随机且无序的。我需要创建一个函数,在SQL查询中动态地从syn_data
列提取前N条记录。
例如:当我给定参数2时,我希望获取syn_data
列中的前2条记录:
{
"7458": {
"syn_idx": [724966, 125940, 727242],
"score": 5.0,
"custom_score": 1.0
},
"1742": {
"syn_idx": [119294, 119321],
"score": 5.0,
"custom_score": 1.0
}
}
我正在使用PostgreSQL 14.1版本。