M
M
mitaichik2015-09-09 17:37:50
PostgreSQL
mitaichik, 2015-09-09 17:37:50

How to search through an array of complex types?

Hello.
I have a complex type user_rating :
userId : int
isExpert : bool
rating : integer
There is a table tbl_ratings
id : int
ratings : user_rating[]
As you can see, the ratings field is an array of the user_rating complex type.
All rows must be selected from this table, the ratings field (array) contains at least one element with isExpert = true.
I found a solution how to make conditions for a specific element:
SELECT * FROM tbl_ratings WHERE (ratings[1]."isExpert") = true
But how can I make it search the entire array? That is to remove this index 1?
Thanks in advance )

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mitaichik, 2015-09-09
@mitaichik

In general, I did not find anything better than writing a simple function:

CREATE OR REPLACE FUNCTION acc_has_expert_rating(ratings acc_rating[])
    RETURNS bool AS
$$
DECLARE
    rating acc_rating; 
BEGIN

  FOREACH rating IN ARRAY ratings
  LOOP 
      IF rating."isExpert" THEN 
        RETURN TRUE;
      END IF;
  END LOOP;

  RETURN false;
END;
$$
LANGUAGE 'plpgsql';

A
Andrey Nikiforov, 2015-09-09
@eoffsock

Found a possible solution, try:

SELECT * FROM tbl_ratings WHERE id IN 
    (SELECT id FROM 
        (SELECT id, unnest(ratings) AS list_item FROM tbl_ratings) explode
        WHERE (explode.list_item).isExpert = true)

K
krypt3r, 2015-09-10
@krypt3r

But how to make it search the entire array?

ANY()? ALL()?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question