简体   繁体   English

MySQL选择最后一个ID与COUNT(*)

[英]Mysql select last id vs COUNT(*)

SELECT id FROM store ORDER BY id DESC LIMIT 1
SELECT COUNT(*) FROM store

I have a table, ID is auto increment. 我有一张桌子,ID是自动递增的。 I try to count the rows, since my id is auto increment from 1, so last id will be the same value of rows 我尝试计算行数,因为我的ID是从1开始自动递增的,所以最后一个ID将是行的相同值

I was wondering which query can have better performance SELECT last id or use COUNT 我想知道哪个查询可以具有更好的性能SELECT last id或使用COUNT

The first might perform better. 第一个可能会更好。

The second is accurate and you should use it. 第二个是准确的,您应该使用它。 The id's are not guaranteed to have no holes. ID不能保证没有孔。 There will definitely be gaps if you have deletes. 如果删除,肯定会有空白。

Assuming id is a primary key, both can be satisfied using the index, which should be faster than reading the entire table. 假设id是主键,则可以使用索引来满足这两个要求,索引比读取整个表要快。

If you're using MyISAM then go with COUNT for sure! 如果您使用的是MyISAM,请确定要使用COUNT! That value is stored for each table anyway, so it doesn't even need to refer to the table content. 无论如何,该值都是为每个表存储的,因此它甚至不需要引用表内容。 But it's different for InnoDB. 但是对于InnoDB来说是不同的。 It has to actually count the rows. 它必须实际计算行数。 But still I would use COUNT. 但是我仍然会使用COUNT。 Not so often for InnoDB though... 但是对于InnoDB来说并不常见...

I would go with count(*) since that's optimized in MySQL and it guarantees a correct answer. 我会使用count(*)因为它在MySQL中进行了优化,并且可以保证正确的答案。 You can always delete rows so relying on the last id would not be a good idea. 您始终可以删除行,因此依靠最后一个id并不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM