【问题标题】:PostgreSQL function return multiple distinct typesPostgreSQL 函数返回多种不同的类型
【发布时间】:2021-04-30 15:56:45
【问题描述】:

函数是否可以返回多个不同的类型?

例子:

我有以下表格:gamesgames_roundsgames_players

现在要通过 id 加载完整游戏,我需要先从 games 加载它,然后通过执行 where game_id = $1games_rounds 加载所有回合,然后对 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_usersgames_roundsgames 的关系是多对一的,查询在实际应用中得到了简化,有更多的行和一些连接

【问题讨论】:

  • 这一切看起来就像一个简单的查询,请提供每个表的示例数据和所需的输出
  • @eshirvana 我已经编辑了帖子以添加示例查询和架构,由于 games_users 和 games_rounds 的多对一关系,这无法在一个查询中完成

标签: sql postgresql plpgsql database-optimization


【解决方案1】:

如果我理解正确这是您想要做的,您可以使用refcursor

create procedure getGamedata(gameid int,result_one inout refcursor, result_two 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;

【讨论】:

  • 谢谢,但就像我描述的那样,一场比赛可以有多个 games_users 和 games_rounds,他们都已经从不同的桌子加入,我对你的方法的担忧是,如果有 20 轮和 6玩家们,那不是返回 120 行,然后我需要减少和删除重复项吗?
  • @Dr.ink ,刷新
猜你喜欢
  • 2022-01-24
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多