哪个是获取 MySQL 查询总行数的最快方法?
您可以使用聚合COUNT(*)的子查询来获取总行数。
让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentAge int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(StudentFirstName,StudentAge) values('John',23); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Larry',21); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Johnny',23); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Chris',21); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('David',23); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('James',21); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Jace',24); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Mike',21); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Robert',25); mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Mike',22);
以下是使用select语句显示表中所有记录的查询-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+------------------+------------+ | StudentId | StudentFirstName | StudentAge | +-----------+------------------+------------+ | 1 | John | 23 | | 2 | Larry | 21 | | 3 | Johnny | 23 | | 4 | Chris | 21 | | 5 | David | 23 | | 6 | James | 21 | | 7 | Jace | 24 | | 8 | Mike | 21 | | 9 | Robert | 25 | | 10 | Mike | 22 | +-----------+------------------+------------+ 10 rows in set (0.00 sec)
以下是获取MySQL查询的总行数并设置所有列值的查询-
mysql> select StudentFirstName,(select count(*) from DemoTable) AS Total_Count from DemoTable limit 10;
这将产生以下输出-
+------------------+-------------+ | StudentFirstName | Total_Count | +------------------+-------------+ | John | 10 | | Larry | 10 | | Johnny | 10 | | Chris | 10 | | David | 10 | | James | 10 | | Jace | 10 | | Mike | 10 | | Robert | 10 | | Mike | 10 | +------------------+-------------+ 10 rows in set (0.03 sec)