For example I have table users
(id, name, email). There is table photos
(id, value)
There is a table userphotos
which consists of relations:
user_id, photo_id.
I need a function to fetch all users with their photos in such a way:
- id1 name1 email1 photos1
- id2 name2 email2 photos2
etc.
Number of photos for a user is not known.
How to create plpgsql function to create such results?
CREATE OR REPLACE FUNCTION test_function()
RETURNS TABLE(id int, name character varying, email character varying, photos int[]) AS $
DECLARE
u RECORD;
BEGIN
FOR u IN SELECT * FROM users LOOP
return NEXT u; -- will return user without photos
-- but how to populate u with photos as array
-- got from query:
-- SELECT photo_id FROM userphotos WHERE user_id = u.id
END LOOP;
END;
$ LANGUAGE plpgsql
PostgreSQL ver. 9.0.