我应该使用 COUNT(*) 来获取 MySQL 中的所有记录吗?
mysqlmysqli database
每当您想要列的所有值(例如非空值)时,请使用 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)
假设您的列没有空值,那么 count(*) 和 count() 会给出相同的结果。
但在我们的示例中,BookId 列有一些空值。在这种情况下,count(*) 和 count() 都会给出不同的结果。
这是使用 count(*) − 的查询
mysql> select count(*) as AllValue from CountingDemo;
输出
+----------+ | AllValue | +----------+ | 5 | +----------+ 1 row in set (0.00 sec)
这是使用 count() 的查询,由于它不会考虑计算空值,因此会给出另一个结果。查询如下 −
mysql> select count(BookId) as AllvalueWhichisNotnull from CountingDemo;
输出
+------------------------+ | AllvalueWhichisNotnull | +------------------------+ | 3 | +------------------------+ 1 row in set (0.00 sec)