问题描述
示例:
我有以下表格:games
、games_rounds
和 games_players
现在要通过 id
加载完整游戏,我需要首先从 games
加载它,然后通过执行 games_rounds
从 where game_id = $1
加载所有回合,然后执行games_players
也是如此,这是对数据库的 3 次不同调用,能否以某种方式将其优化为函数?
简单演示:
// Basic schema (all game_id rows have an index on them):
create table games (id serial,state smallint,value int);
create table games_rounds (id serial,game_id int,outcome int);
create table games_users (game_id int,user_id int,order int);
// Example query to get full game data:
select id,state,value from games where id = 1
select id,outcome from games_rounds where game_id = 1
select user_id,order from games_users where game_id = 1
正如您在上面看到的,games_users
和 games_rounds
在与 games
的关系中是多对一的,在实际应用程序中简化了查询,有更多的行和一些连接
解决方法
如果我理解正确,这就是你想要做的,你可以使用 refcursor
create procedure getGamedata(gameid int,result_one inout refcursor,result_two inout refcursor,result_three inout refcursor)
as
$$
begin
open result_one for
select id,state,value from games where id = gameid;
open result_two for
select id,outcome from games_rounds where game_id = gameid;
open result_three for
select user_id,order from games_users where game_id = gameid;
end;
$$
language plpgsql;