我有两个表:old_data
和 new_data
。
两个表都有列: ID、日期、值
我想删除“old_data”中不在“new_data”中的任何行,但只删除选定日期之间的行。
这在 psql 中有效:
DELETE FROM old_data
WHERE (id, date) NOT IN (SELECT id, date FROM new_data) AND
id = my_id AND date >= 'my_start_date' AND date <= 'my_end_date';
每个 ID 的开始/结束日期都不同,因此我必须为每个不同的 ID 分别运行 DELETE。 “new_data”中大约有 1000 个不同的 ID。
问题是它非常慢 - 当“old_data”有 1500 万行而“new_data”有 100,000 行时需要一个小时。
有没有更有效的方法来做到这一点?
最佳答案
在运行查询之前创建这些索引。
create index old_data_id_index
on old_data
using btree (id);
create index old_data_date_index
on old_data
using btree(date);
create index new_data_id_index
on new_data
using btree(id);
create index new_data_date_index
on new_data
using btree(date);
关于sql - postgres 中的删除速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472191/