count(*) 其中 cond = val,或 count(cond = val)
这两种方法有什么区别?
select count(*) from `table` where `column` = 'value';
对
select count(`column` = 'value') from `table`;
我来说,他们似乎也在做同样的事情;我认为数据库的情况并非如此。一种方法是否比另一种更好地利用索引?
在本例中,我使用 MySQL,但这里首选一般答案。
What is the difference between these two methods?
select count(*) from `table` where `column` = 'value';
and
select count(`column` = 'value') from `table`;
To me they seem to do the same thing; I assume this is not the case for the database. Does one method leverage indexes better than the other?
In this case I use MySQL but a general answer is preferred here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
count(
column
= 'value')通常似乎意味着您正在计算比较的布尔结果,这应该计算表中的所有行,尽管您的特定 DBMS 可能有例外。
根据 where 子句过滤查询。如果您需要为不同的数据库编写类似的查询,这将是一个好习惯。
count(
column
= 'value')Would generally seem to imply you are counting the boolean result of the comparison, which should count all the rows in the table, though perhaps your particular DBMS has an exception.
Filter the query on the where clause. It will be a good habit in case you ever need to write a similar query for a different database.
通过 mySQL 运行示例会产生不同的结果。您发布的第二个查询不限制结果集 - 返回所有行。然而,第一个查询确实如此。
Running your samples through mySQL yields different results. The second query you posted doesn't restrict the result set - all rows are returned. The first query, however, does.