---
title: "【mysql】count 联想到的"
author: "cectsky"
date: "2013-04-15T18:42:18Z"
tags: []
categories: ["数据库"]
slug: "mysql-count"
draft: false
lastmod: "2013-04-15T18:42:18Z"
id: 1847807
url: "https://cectsky.iteye.com/blog/1847807"
---

今天使用count的时候发现了一些问题。回顾一下，温故而知新，可以为师矣~![酷](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-cool.gif "酷") &lt;2,0&gt;

 

 

语法： []()[`COUNT( expr )`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/functions.html#function_count)

&lt;PS:count is a kind of aggregate functions in mysql.也就是我们说的group by配合使用的&gt;

 

Returns a count of the number of **non-`NULL`**  values of  *`expr`*  in the rows retrieved by a [`SELECT`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/sql-syntax.html#select "13.2.9. SELECT Syntax") statement. The result is a [`BIGINT`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/data-types.html#integer-types "11.2.1. Integer Types (Exact Value) - INTEGER,         INT, SMALLINT,         TINYINT, MEDIUMINT,         BIGINT") value.

 

[`COUNT(*)`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/functions.html#function_count) is somewhat different in that it returns a count of the number of rows retrieved, **whether or not** they contain `NULL` values.

 

[`COUNT(*)`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/functions.html#function_count) is **optimized** to return very quickly if the [`SELECT`](http://www.ostools.net/uploads/apidocs/mysql-5.5-en/sql-syntax.html#select "13.2.9. SELECT Syntax") retrieves from one table, no other columns are retrieved, and there is no `WHERE` clause. For example:

 

 

```
mysql> SELECT COUNT(*) FROM student;
```

 

 

 This optimization applies only to `MyISAM` tables only, because an exact row count is stored for this storage engine and can be accessed very quickly. For transactional storage engines such as `InnoDB`, storing an exact row count is more problematic because multiple transactions may be occurring, each of which may affect the count.

摘了一部分官方doc,重点词汇已经加粗了.

 

想说的是：

1、count(\*) 使用场合：MyISAM引擎、没有where条件的sql，这种情况mysql是做过优化的。

   目前市面上充斥着用count(具体的列)替换count(\*) 可以带来性能提升的言论,其实**不然**,这和store engine有莫大的关系,晚些时候我再写点关于InnoDB and MyISAM的一些区别。

    我做了一个测试,数据114w,

    count(1) : 487 ms

    count(col1) : 531ms

    count(\*):   489ms

2、count(\*) 返回记录和是否是null无关

    比如一个Table test(col1,col2) 数据只有2条，都为null,null

    

```
mysql > select count(*) from test;
mysql > select count(col1) from test;
```

 结果在本文第一行末尾已经给出，看看你能张口说出来不? 哈哈![吻](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-kiss.gif "吻")