簡體   English   中英

postgres中帶有select語句的數組的交集

[英]Intersection of array with select statement in postgres

我正在嘗試將select語句與在循環中動態計算的數組進行相交,然后測量每個相交查詢所花費的時間。

因此,在循環的第一次迭代中,我希望查詢如下所示:

'select sub_id from table where main_id=1 INTERSECT select array[''80'']';

在第二次迭代中:

'select sub_id from table where main_id=1 INTERSECT select array[''80'', ''81'']';

等等,並測量每次迭代執行查詢所花費的時間。

運行此腳本時,出現錯誤:

上下文:PL / pgSQL函數inline_code_block在分配時

對應於我初始化query1的行。 如何更正對query1的分配? 我正在使用PostgreSQL 9.1。

arr := '{}';
for j in 80..120 loop
  arr := array_append(arr, j::text);
  query1 := 'select sub_id from table where main_id=1 INTERSECT' || ' select unnest(arr)';
  execute 'explain (analyse, format json) ' || query1 into p;
  t := (p->0->>'Planning Time')::float + (p->0->>'Execution Time')::float;
  total_time := total_time + t;
end loop;

execute的查詢文本無法引用調用范圍中的變量。 您必須using like將變量作為參數傳遞:

query1 := 'select sub_id from YourTable where main_id=1 INTERSECT select unnest($1)';
execute 'explain (analyse, format json) ' || query1 using arr into p;
                                                    ^^^^^^^^^

rextester.com上的工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM