PostgreSQL JOIN with array type with array elements order, how to implement?

前端 未结 4 1137
梦谈多话
梦谈多话 2020-12-02 13:04

I have two tables in database:

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

This table contains come data row with

相关标签:
4条回答
  • 2020-12-02 13:35
    SELECT I.* FROM items AS I 
    WHERE I.id IN (SELECT UNNEST(id_items) FROM some_chosen_data_in_order 
    (ARRAY[SELECT S.id_items FROM some_chosen_data_in_order  WHERE id = ?])
    
    0 讨论(0)
  • 2020-12-02 13:38

    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)
    
    0 讨论(0)
  • 2020-12-02 13:49
    SELECT t.*
    FROM unnest(ARRAY[1,2,3,2,3,5]) item_id
    LEFT JOIN items t on t.id=item_id
    

    The above query select items from items table with ids: 1,2,3,2,3,5 in that order.

    0 讨论(0)
  • 2020-12-02 13:49
    select distinct on (some_chosen_data_in_order.id)
      some_chosen_data_in_order.*,
       array_to_json( array_agg(row_to_json( items))
      over ( partition by some_chosen_data_in_order.id ))
    from some_chosen_data_in_order
      left join items on items.id = any (some_chosen_data_in_order.id_items)
    

    0 讨论(0)
提交回复
热议问题