确定记录是否存在的最快方式 [英] Fastest way to determine if record exists

查看:103
本文介绍了确定记录是否存在的最快方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示...我试图找出最快的方式用最少的开销来确定一个记录是否存在于表中。

As the title suggests... I'm trying to figure out the fastest way with the least overhead to determine if a record exists in a table or not.

示例查询:

SELECT COUNT(*) FROM products WHERE products.id = ?;

    vs

SELECT COUNT(products.id) FROM products WHERE products.id = ?;

    vs

SELECT products.id FROM products WHERE products.id = ?;

c $ c>'TB100' ...第一个和第二个查询将返回完全相同的结果(例如... 1 会话)。最后一个查询将按预期返回'TB100',如果表中不存在 id ,则不返回任何内容。

Say the ? is swapped with 'TB100'... both the first and second queries will return the exact same result (say... 1 for this conversation). The last query will return 'TB100' as expected, or nothing if the id is not present in the table.

目的是找出 id 是否在表格中。如果没有,程序将插入记录,如果是,程序将跳过它或执行UPDATE查询基于其他程序逻辑超出了这个问题的范围。

The purpose is to figure out if the id is in the table or not. If not, the program will next insert the record, if it is, the program will skip it or perform an UPDATE query based on other program logic outside the scope of this question.

哪个更快,有更少的开销? (每次程序运行将重复上万次,并且每天将运行许多次)。

Which is faster and has less overhead? (This will be repeated tens of thousands of times per program run, and will be run many times a day).

(通过M $提供的JDBC驱动程序从Java运行此查询M $ SQL Server)

(Running this query against M$ SQL Server from Java via the M$ provided JDBC driver)

推荐答案

SELECT TOP 1 products.id FROM products WHERE products.id =?; 会胜过所有建议,因为它会终止执行找到第一条记录。

SELECT TOP 1 products.id FROM products WHERE products.id = ?; will outperform all of your suggestions as it will terminate execution after it finds the first record.

这篇关于确定记录是否存在的最快方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆