This is my dummy setup:
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
);
Example row in containers
:
id positions
1 [4, 2, 3]
What I'm trying to accomplish is to use the positions
in containers
to dictate the order in which bits are returned. This seems like it might be easier than using a smallint position
column in bits
that has values like 0, 1, 2, 3, and must all be updated when the user reorders the bits.
In essence, what I'm trying to do is use the positions
array in ORDER BY
, e.g. (pseudo-code):
SELECT b.id, b.data FROM bits b, container c WHERE b.container_id = 1 ORDER BY (jsonb_array_elements(c.positions));
The desired output would be:
id data
4 {"banner": "This is a message!"}
2 {"name": "Bob"}
3 {"playlistId": 3}
How do I accomplish this? I'm using Postgres 10.7.