我应该不算(*)吗? [英] Should I COUNT(*) or not?
问题描述
我知道执行这样的查询通常不是一个好主意:
I know it's generally a bad idea to do queries like this:
SELECT * FROM `group_relations`
但是当我只想计数时,我应该进行此查询,因为这允许更改表,但仍然产生相同的结果.
But when I just want the count, should I go for this query since that allows the table to change but still yields the same results.
SELECT COUNT(*) FROM `group_relations`
或更具体的
SELECT COUNT(`group_id`) FROM `group_relations`
我觉得后者可能会更快,但是还有其他需要考虑的东西吗?
I have a feeling the latter could potentially be faster, but are there any other things to consider?
更新:在这种情况下,我使用的是InnoDB,对不起,因为它不够具体.
Update: I am using InnoDB in this case, sorry for not being more specific.
推荐答案
如果所讨论的列不是NULL,则两个查询都是等效的.当group_id包含空值时,
If the column in question is NOT NULL, both of your queries are equivalent. When group_id contains null values,
select count(*)
将计算所有行,而
select count(group_id)
仅计算group_id不为null的行.
will only count the rows where group_id is not null.
此外,某些数据库系统(例如MySQL)在请求count(*)时进行了优化,从而使此类查询比特定查询快一点.
Also, some database systems, like MySQL employ an optimization when you ask for count(*) which makes such queries a bit faster than the specific one.
就个人而言,当我计数时,我正在做count(*)以便安全地使用空值.
Personally, when just counting, I'm doing count(*) to be on the safe side with the nulls.
这篇关于我应该不算(*)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!