mysql中的count()函數使用

來源:互聯網
上載者:User

標籤:col   opera   sql   span   效率   欄位   com   select   val   

有時候總認為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()函數使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.