小编Ngi*_*giW的帖子

Postgres 按 Json 数组排序

我有以下 json 存储在 jsonb 字段中。对于代表产品的每条记录,它包含各种类别,每个类别中的 a 是优先级。

[
      {
        "priority": 0,
        "description": "",
        "categoryName": "Cars",
        "title": ""
      },
      {
        "priority": 1,
        "description": "",
        "categoryName": "Trucks",
        "title": ""
      },
      {
        "priority": 2,
        "description": "",
        "categoryName": "Vans",
        "title": ""
      }
    ]
Run Code Online (Sandbox Code Playgroud)

我想使用优先级字段动态地按各种类别对数据进行排序,这样,如果我显示类别 Cars 中的所有产品,我将按 0 数组元素排序,如果我显示类别 Vans 中的所有产品, 我按 2 数组元素排序。

目前,要按第一个数组元素排序,我可以这样做:

ORDER BY OBJECT_DATA->'productCategories'->0->>'priority' 
Run Code Online (Sandbox Code Playgroud)

但是,我想通过首先选择数组值 ( categoryName) 然后使用数组值来选择其优先级来排序。

例如:按卡车排序->优先级 (1)

我正在使用 PostgresSQL 9.6。

postgresql json postgresql-9.6

5
推荐指数
1
解决办法
7187
查看次数

标签 统计

json ×1

postgresql ×1

postgresql-9.6 ×1