2017-08-28 70 views
0

我有以下功能需要showid參數,返回與該所有數據的一行showid從不同的表電影 TYPE。我想添加不帶任何參數的函數的另一個版本,並返回有關所有電影的詳細信息,每行電影到電影 TYPE。Postgres的函數返回多行

電影類型:

CREATE TYPE movie as (          
id BIGINT, 
title TEXT, 
year INT, 
overview TEXT, 
actors TEXT[], 
directors TEXT[], 
genres TEXT[] 
); 

功能movie_details:

CREATE OR REPLACE FUNCTION movie_details (movieid BIGINT) 
RETURNS SETOF movie 
LANGUAGE plpgsql 
AS $$ 

DECLARE 
show SHOWS; 
film FILMS; 
movie_actors TEXT[]; 
movie_directors TEXT[]; 
movie_genres TEXT[]; 

BEGIN 

SELECT * INTO show FROM shows s 
WHERE s.showid = movieid; 

SELECT f.* INTO film FROM films F 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(concat_ws(' ', fname, mname, lname)) INTO movie_actors FROM people p 
JOIN actin a USING (personid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(concat_ws(' ', fname, mname, lname)) INTO movie_directors FROM people p 
JOIN direct d USING (personid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(g.name) INTO movie_genres from genres g 
JOIN showgenres USING (genreid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

RETURN QUERY 
SELECT show.showid, show.title, film.year, show.overview, movie_actors, movie_directors, movie_genres; 
END; 
$$; 
+0

使用HTTPS的組合://www.postgresql .org/docs/9.6/static/arrays.html和https://www.postgresql.org/docs/9.6/stati c/plpgsql-cursors.html應該很容易完成你所需要的。首先打開遊標,然後用結果填充多維數組。 – PerunSS

回答

0

這是我如何做的:

CREATE OR REPLACE FUNCTION movie_details() 
RETURNS SETOF movie 
LANGUAGE plpgsql 
AS $$ 

DECLARE 
show SHOWS; 
film FILMS; 
movie_actors TEXT[]; 
movie_directors TEXT[]; 
movie_genres TEXT[]; 
movieid BIGINT; 
BEGIN 
FOR movieid IN SELECT showid FROM shows 
LOOP 
SELECT * INTO show FROM shows s 
WHERE s.showid = movieid; 

SELECT f.* INTO film FROM films f 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(concat_ws(' ', fname, mname, lname)) INTO movie_actors FROM people p 
JOIN actin a USING (personid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(concat_ws(' ', fname, mname, lname)) INTO movie_directors FROM people p 
JOIN direct d USING (personid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 

SELECT array_agg(g.name) INTO movie_genres from genres g 
JOIN showgenres USING (genreid) 
JOIN shows s USING (showid) 
WHERE s.showid = movieid; 
RETURN QUERY SELECT show.showid, show.title, film.year, show.overview, movie_actors, movie_directors, movie_genres; 
END LOOP; 
RETURN; 
END; 
$$;;