1. 程式人生 > >mysql中的count()函數使用

mysql中的count()函數使用

gre arch str pan 表達式 ble 執行 int mar

有時候總認為count(*)會比count(1)或者count(column name)慢,事實上是分情況處理。

比如:

---初始化語句

建立一張表並插入數據:

create table test2 (id BIGINT PRIMARY key, name varchar(24))ENGINE=INNODB;

insert into test2(id,name)values(1,null);

insert into test2(id,name)values(2,‘name1‘);

insert into test2(id,name)values(3,‘name2‘);

執行下面的select語句:

select count(*) from test2 ; //結果是:3

select count(id) from test2 ; //結果是:3

select count(name) from test2 ; //結果是:2

select count(name) from test2 where name is null; //結果是:0

count(1)指的並不是計算1的個數,而是指表的第一個字段,如果第一個字段沒有建立索引,他的效率是很低的;

而且count(column name)默認查詢的是指定字段非空的個數,如果你想查詢數據的所有行數,恰巧指定字段又是

一個可存在空庫數據的字段,那麽得到的數據就不會是期望的值。再來說一下count(),在上述的count(column name)

查詢方式中,如果指定的column為限制為非空,那麽mysql會將上述表達式轉化為count()來進行查詢。所以如果想

要查詢數據大小,在mysql中建議使用count(*)來執行,含義明了,速度還快。

mysql中的count()函數使用