What's the fastest way to check that entry exists in database?

旧街凉风 提交于 2020-01-02 03:30:11

问题


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!


回答1:


In most situations, COUNT(*) is faster than COUNT(id) in MySQL (because of how grouping queries with COUNT() 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 use EXISTS

simple:

( SELECT COUNT(id) FROM table_name ) > 0

a bit faster:

( SELECT COUNT(*) FROM table_name ) > 0

much faster:

EXISTS (SELECT * FROM table_name)



回答2:


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(*) and count(field). When in doubt, count(*)

As for checking that a table is not empty...

SELECT EXISTS(SELECT 1 FROM table)



来源:https://stackoverflow.com/questions/7569137/whats-the-fastest-way-to-check-that-entry-exists-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!