获取 MySQL 查询的总行数最快的方法是什么?
mysqlmysqli database
您可以使用带有聚合 COUNT(*) 的子查询来获取总行数。
首先我们创建一个表 −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentAge int ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(StudentFirstName,StudentAge) values('John',23); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Larry',21); Query OK, 1 row affected (0.40 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Johnny',23); Query OK, 1 row affected (0.43 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Chris',21); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('David',23); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('James',21); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Jace',24); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Mike',21); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Robert',25); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(StudentFirstName,StudentAge) values('Mike',22); Query OK, 1 row affected (0.23 sec)
以下是使用 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)