我應使用 COUNT(*) 來獲得 MySQL 中的所有記錄嗎?
當需要獲得一個類似列 non null 的所有值時 ,使用 count(*)。這比使用 count() 方法要快。
使用 count(*) 的語法如下 -
select count(*) as anyVariableName from yourTableName;
為了理解上述概念,我們首先建立一個表格。建立表格的查詢如下 -
mysql> create table CountingDemo -> ( -> BookId int -> ); Query OK, 0 rows affected (0.60 sec)
使用 insert 命令向表格中插入一些記錄。查詢如下 -
mysql> insert into CountingDemo values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into CountingDemo values(); Query OK, 1 row affected (0.17 sec) mysql> insert into CountingDemo values(200); Query OK, 1 row affected (0.12 sec) mysql> insert into CountingDemo values(300); Query OK, 1 row affected (0.16 sec) mysql> insert into CountingDemo values(); Query OK, 1 row affected (0.12 sec)
使用 select 語句顯示錶格中的所有記錄。查詢如下 -
mysql> select *from CountingDemo;
輸出
+--------+ | BookId | +--------+ | 100 | | NULL | | 200 | | 300 | | NULL | +--------+ 5 rows in set (0.00 sec)
假設你的列沒有 null 值,那麼 count(*) 和 count() 會得到相同的結果。
但在我們的示例中,BookId 列有一些 null 值。在這種情況下,count(*) 和 count() 會得到不同的結果。
這裡使用 count(*) 的查詢 -
mysql> select count(*) as AllValue from CountingDemo;
輸出
+----------+ | AllValue | +----------+ | 5 | +----------+ 1 row in set (0.00 sec)
這裡使用 count() 的查詢,它不會將 null 值算在內,因此會得到另一個結果。查詢如下 -
mysql> select count(BookId) as AllvalueWhichisNotnull from CountingDemo;
輸出
+------------------------+ | AllvalueWhichisNotnull | +------------------------+ | 3 | +------------------------+ 1 row in set (0.00 sec)
廣告