说明 - 只插入一行

Jus*_*tMe 5 sql postgresql explain postgresql-9.3

我正在尝试手动保存优化程序计划以进行进一步分析,如下所示:

do $$
declare
tmp text;
begin
  explain
    select * from public.some_table where 1=2 into tmp;
  insert into public.plans(plan) values (tmp);
end; $$
Run Code Online (Sandbox Code Playgroud)

但是当我稍后选择它时,我看到它只从explain语句中保存了第一行:

Result  (cost=0.00..82.97 rows=1 width=114)
Run Code Online (Sandbox Code Playgroud)

如何保存整个计划呢?

小智 1

因为explain不能像 a 那样使用,SELECT这有点棘手,您需要动态 SQL。

以下对我有用:

do
$$
declare
   plan_line record;
begin
   for plan_line in execute 'explain select * from public.some_table where 1=2' loop
      insert into plans values (plan_line."QUERY PLAN");
   end loop;
end;
$$
Run Code Online (Sandbox Code Playgroud)

将要解释的语句放在字符串中会使事情变得更加复杂。

如果我经常需要这样做,我可能会创建一个函数来执行此操作:

create or replace function explain(to_explain text)
  returns setof text
as
$$
declare
  plan_line record;
begin
   for plan_line in execute 'explain '||to_explain loop
      return next plan_line."QUERY PLAN";
   end loop;
end;
$$
language plpgsql;
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情:

insert into plans 
select * 
from explain('select ...');
Run Code Online (Sandbox Code Playgroud)