postgresql 如何根据接收到的结果来改进环路的性能?

okxuctiv  于 2023-01-02  发布在  PostgreSQL
关注(0)|答案(1)|浏览(263)

我必须在数据表中进行查询,根据收到的结果数量(从0到X),我必须在另一个表中添加信息:

begin
                for code in select object from data where subject = 'subject1'
                and predicate = '#type' 
                and object like '/core%'
                loop
               select id into categories from categories  where id_categories  = code;
               if found then
    
                insert into fiche_categories (fiche_id, categories_id) values (fiche, categories ) on conflict (fiche, categories ) do NOTHING;
               end if;
end loop;
end;

我如何提高性能?
谢谢

qv7cva1a

qv7cva1a1#

首先不要使用命令式循环,编写声明式SQL:

insert into fiche_categories (fiche_id, categories_id)
select fiche, categories.id
  from data
  join categories on id_categories = data.object;
  where data.subject = 'subject1'
    and data.predicate = '#type' 
    and data.object like '/core%'
on conflict (fiche, categories) do nothing;

此外,为了提高数据库的速度,不要使用EAV model,并确保表有适当的索引支持。

相关问题