views:

260

answers:

1

Hello

I have two tables in database:

CREATE TABLE items(
 id SERIAL PRIMARy KEY,
 ... some other fields
);

This table contains come data row with unique ID.

CREATE TABLE some_choosen_data_in_order(
 id SERIAL PRIMARy KEY,
 id_items INTEGER[],

);

This table contains array type field. Each row contains values of IDs from table "items" in specyfic order. For example: {2,4,233,5}.

Now, I want to get data from table "items" for choosen row from table "some_choosen_data_in_order" with order for elements in array type.

The my attempt is JOIN:

SELECT I.* FROM items AS I 
JOIN some_choosen_data_in_order AS S ON I.id = ANY(S.id_items) WHERE S.id = ?

Second attempt was subquery like:

SELECT I.* FROM items AS I 
WHERE I.id = ANY 
(ARRAY[SELECT S.id_items FROM some_choosen_data_in_order  WHERE id = ?])

But none of them keep IDs order in array field. Could You help me, how to get data from "items" table with correspond with array IDs order from "some_choosen_data_in_order" table for specyfic row?

A: 

Probably normalizing your table would be the best advice I can give you.

The int_array contrib module has an idx function that will give you the int's index position in the array. Also there is an idx function on the snippets wiki that works for array's of any data types.

SELECT i.*, idx(id_items, i.id) AS idx
FROM some_chosen_data_in_order s
JOIN items i ON i.id = ANY(s.id_items)
ORDER BY idx(id_items, i.id)
Scott Bailey
It's clearly what I need. Thanx! I'm denormalizing my database due to efficiency reasons.
Adiasz