如何按主键 ID 的 JSONB 数组指定的顺序 SELECT 行?

How to SELECT rows in an order dictated by a JSONB array of primary key IDs?

这是我的虚拟设置:

CREATE TABLE containers (
    id SERIAL PRIMARY KEY,
    positions jsonb
);
CREATE TABLE bits (
    id SERIAL PRIMARY KEY,
    container_id integer REFERENCES containers(id) ON DELETE CASCADE ON UPDATE CASCADE,
    data jsonb
);

containers 中的示例行:

id  positions
1   [4, 2, 3]

我想要完成的是使用 containers 中的 positions 来指定返回位的顺序。这似乎比在 bits 中使用具有 0、1、2、3 等值的 smallint position 列更容易,并且必须在用户重新排序位时全部更新。

本质上,我想做的是在 ORDER BY 中使用 positions 数组,例如(伪代码):

SELECT b.id, b.data FROM bits b, container c WHERE b.container_id = 1 ORDER BY (jsonb_array_elements(c.positions));

所需的输出为:

id  data
4   {"banner": "This is a message!"}
2   {"name": "Bob"}
3   {"playlistId": 3}

我该如何做到这一点?我正在使用 Postgres 10.7。

您需要使用 jsonb 函数来执行此操作。

请尝试这样的操作:

select b.*
  from bits b
       join containers c
         on c.id = b.container_id
       join lateral jsonb_array_elements_text(c.positions) 
                      with ordinality as p(id, rn)
         on p.id::int = b.id
 where b.container_id = 1
 order by p.rn::int