如何在Postgresql中解释SELECT ... JOIN ... INTO的结果?

时间:2017-05-19 20:03:43

标签: postgresql join psql

我想选择一个连接的行然后将它存储在一个PLSQL变量中,然后我可以用一些理智的方式使用它。

我最好的选择似乎是RECORD类型,但它并没有让我到任何地方:

DECLARE cur_acct_and_balance RECORD;
BEGIN
  -- we start from _acct
  SELECT INTO cur_acct_and_balance *
  FROM Accounts acct JOIN Balances bal ON acct.id = bal.account_id
  WHERE acct.id = _acct.id AND bal.currency = _currency;

  -- raise the variable, maybe we learn something...
  raise exception '%', cur_acct_and_balance;

所以...我设法将某些放在cur_acct_and_balance变量中,但是什么? :D我尝试将结果变量作为异常提升,检查它,但是在解释结果时没有运气:

ERROR:  (5707,5706,,,"{""logid"":""A/1/2/0""}","2017-05-19 21:44:40.672074","2017-05-19 21:44:40.672074",3170,5707,0,191,"2017-05-19 21:44:40.662101","2017-05-19 21:44:40.662101")

哪个非常没用。如果我尝试将其评估为cur_acct_and_balance.acct IS NOT NULL,我会

ERROR:  record "cur_acct_and_balance" has no field "acct"

如果我尝试将其评估为cur_acct_and_balance.acct.id IS NOT NULL

ERROR:  missing FROM-clause entry for table "acct"

我发现没有好的资源谷歌搜索,所以我希望这里的好人可以得到一些帮助^ _ ^

更新

现在我只是重写了不使用连接的函数,但是我仍然有兴趣知道,我猜测连接变量应该更高效。

2 个答案:

答案 0 :(得分:1)

您的记录不会引用原始表,而只会引用其列。你只需要一组加入两张桌子。因此,您必须以这种方式访问​​您的列:

cur_acct_and_balance.column_name

您的IF声明:

IF cur_acct_and_balance.id IS NOT NULL THEN
      --If body
END IF

答案 1 :(得分:1)

有几种解决方案:

create temp table a on commit drop as select 1 as x, 2 as y;
create temp table b on commit drop as select 'a'::text as x, 'b'::text as y;
do $$
declare
  r record;
  j jsonb;
begin
  -- Explicyt type conversion
  select a.*, row(b.*)::b as b into r from a,b;
  raise info '%, %, %', r, r.y, (r.b).x; -- Note parenthesizes

  -- Columns aliases
  select a.x as a_x, a.y as a_y, b.x as b_x, b.y as b_y into r from a,b;
  raise info '%, %', r, r.b_y;

  -- JSONB
  select to_jsonb(t.*) into j from (select a.*, to_jsonb(b.*) as b from a,b) as t;
  raise info '%, %', j, j->'b'->>'x';
end $$;

结果:

INFO:  (1,2,"(a,b)"), 2, a
INFO:  (1,2,a,b), b
INFO:  {"b": {"x": "a", "y": "b"}, "x": 1, "y": 2}, a