检查数据库中是否存在该条目的最快方法是什么?
我正在寻找最快的方法来检查条目是否存在...
我一生都在做这样的事情...
SELECT COUNT(`id`) FROM `table_name`
有些人不使用 COUNT(id)
,但是 COUNT(*)
。这样更快吗?
LIMIT 1
怎么样?
PS 当然,对于 id
我指的是主键。
谢谢指教!
I'm looking for the fastest way to check that entry exists...
All my life, I did with something like this...
SELECT COUNT(`id`) FROM `table_name`
Some people don't use COUNT(id)
, but COUNT(*)
. Is that faster?
What about LIMIT 1
?
P.S. With id
I meant primary key, of course.
Thanks in an advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在大多数情况下,
COUNT(*)
比 MySQL 中的COUNT(id)
更快(因为使用COUNT()
进行分组查询的执行方式,它可能会在未来的版本中进行优化,因此两个版本运行相同)。但如果你只想查找是否至少存在一行,你可以使用EXISTS
简单:
快一点:
快得多:
In most situations,
COUNT(*)
is faster thanCOUNT(id)
in MySQL (because of how grouping queries withCOUNT()
are executed, it may be optimized in future releases so both versions run the same). But if you only want to find if at least one row exists, you can useEXISTS
simple:
a bit faster:
much faster:
如果您不担心准确性,
explain select count(field) from table
的速度非常快。http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol /
此链接解释了
count(*)
和count(field)
之间的区别。如有疑问,count(*)
至于检查表是否不为空...
SELECT EXISTS(SELECT 1 FROM table)
If you aren't worried about accuracy,
explain select count(field) from table
is incredibly fast.http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/
This link explains the difference between
count(*)
andcount(field)
. When in doubt,count(*)
As for checking that a table is not empty...
SELECT EXISTS(SELECT 1 FROM table)