Postgres函数返回多行

时间:2017-08-28 21:14:53

标签: postgresql

我在下面的函数中使用了 showid 参数,并从不同的表中将与 showid 相关的所有数据中的一行返回到电影 TYPE。我想添加不带参数的另一个版本的函数,并将有关所有电影的详细信息,一行中的每部电影都返回到电影 TYPE。

电影类型:

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;
$$;

1 个答案:

答案 0 :(得分: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;
$$;;