sql - 将不匹配的 ID 插入列的更快方法

标签 sql postgresql

有没有更快的方法获取table1中存在但table2中不存在的id并将它们插入table2中?

insert into table2 (id) 
select id 
from table1 
where table1.id not in (select id from table2)

最佳答案

除了使用 in 运算符的解决方案之外,请尝试使用 exists 一个

select id
from table1 t1
where not exists (
    select 1
    from table2
    where id = t1.id 
)

如果子查询返回一个空集 not exists 计算结果为 true

外连接

select id
from
    table1 t1
    left join
    table2 t2 on t1.id = t2.id
where t2.id is null

使用explain analyze进行比较

关于sql - 将不匹配的 ID 插入列的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18156459/

相关文章:

python - SQLAlchemy 选择存在限制

mysql - 如何找到在磁盘上创建临时表的 SQL 查询?

sql - 删除 ORACLE 服务器中的保存点

sql - 在 SQL 数据库中设计同义词库的最佳方法?

ruby-on-rails - 如何手动将用户添加到 Rails 应用程序?

postgresql - 在 PostgreSQL 的 WHERE 子句中使用函数结果

mysql - 如何在mysql中对前一行进行求和

postgresql - 在Rust中将时间戳吸收到postgres时,如何避免字符串转换?

POSTGRESQL unaccent 不匹配带有 ñ 的单词

sql - PostgreSQL 9.3 - 比较两组数据而不重复第一组中的值