我有两个联合查询并插入到临时表中。
查询 1
select *
from (
select a.id as id, a.name as name from a
union all
select b.id as id, b.name as name from b
)
查询 2
drop table if exists temporary;
create temp table temporary as
select id as id, name as name
from a;
insert into temporary
select id as id, name as name
from b;
select * from temp;
请告诉我哪个性能更好?
最佳答案
我希望第二个选项有更好的性能,至少在数据库级别。两个版本都需要对 a
和 b
表进行全表扫描。但是第一个版本会创建一个不必要的中间表,仅用于插入目的。
执行两个单独的插入操作的唯一潜在问题是延迟,即某些进程进出数据库可能需要的时间。如果您担心这一点,那么您可以限制为一个插入语句:
INSERT INTO temporary (id, name)
SELECT id, name FROM a
UNION ALL
SELECT id, name FROM b;
这只需要访问一次数据库。
关于postgresql - Postgres - UNION ALL 与 INSERT INTO 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50980784/