我应该使用COUNT(*)来获取MySQL中的所有记录吗?

每当您希望所有值(例如不为null的列)时,都可以使用count(*)。这比使用count()方法要快。

使用count(*)的语法如下-

select count(*) as anyVariableName from yourTableName;

为了理解上述概念,让我们首先创建一个表。创建表的查询如下-

mysql> create table CountingDemo
   -> (
   -> BookId int
   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into CountingDemo values(100);

mysql> insert into CountingDemo values();

mysql> insert into CountingDemo values(200);

mysql> insert into CountingDemo values(300);

mysql> insert into CountingDemo values();

使用select语句显示表中的所有记录。查询如下-

mysql> select *from CountingDemo;

输出结果

+--------+
| BookId |
+--------+
|    100 |
|   NULL |
|    200 |
|    300 |
|   NULL |
+--------+
5 rows in set (0.00 sec)

假设您的列没有null值,那么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)