如何在postgresql中处理执行计划?

q9yhzks0  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(470)

在postgresql中,当我运行时:

EXPLAIN (FORMAT JSON) SELECT * FROM ACCOUNT WHERE TYPE > 'CHK'

我得到:

[
  {
    "Plan": {
      "Node Type": "Seq Scan",
      "Parallel Aware": false,
      "Relation Name": "account",
      "Alias": "account",
      "Startup Cost": 0.00,
      "Total Cost": 13.25,
      "Plan Rows": 87,
      "Plan Width": 276,
      "Filter": "((type)::text > 'CHK'::text)"
    }
  }
]

我怎样才能从那里得到“总成本”?我试过:

SELECT P -> 'Total Cost' FROM (
  EXPLAIN (FORMAT JSON)
  SELECT * FROM ACCOUNT WHERE TYPE > 'CHK'
) X (P)

但我得到了一个错误:

ERROR: syntax error at or near "JSON"
  Position: 51
SQLState:  42601
0ejtzxu1

0ejtzxu11#

explain 总是需要在陈述之前,你不能把它放在陈述的中间。
您可以通过将其 Package 到函数中来执行以下操作:

create or replace function get_plan_cost(p_sql text)
  returns text
as
$$
declare
  l_result jsonb;
begin  
  execute 'explain (format json) ' || p_sql
    into l_result;
  return l_result #>> '{0,Plan,"Total Cost"}';
end;
$$
language plpgsql;
select get_plan_cost($$ SELECT * FROM ACCOUNT WHERE TYPE > 'CHK' $$);

如果不能使用函数,则可以使用带有raise语句的匿名块:

set client_min_messages=notice;
do
$$
declare
  l_sql text := $$ SELECT * FROM ACCOUNT WHERE TYPE > 'CHK' $$;
  l_result jsonb;
begin  
  execute 'explain (format json) ' || l_sql
    into l_result;
  raise notice 'Cost: %', l_result #>> '{0,Plan,"Total Cost"}';
end;
$$
;

但与使用相比,这似乎过于复杂:

explain (format text)
SELECT * FROM ACCOUNT WHERE TYPE > 'CHK';

然后简单地看第一行。

相关问题