如何从 MySQL 实现 Count (*) 作为变量来显示表中的记录数?

mysqlmysqli database更新于 2025/10/2 12:28:17

别名可以用作 MySQL 中的变量名,如以下语法所示 −

select count(*) AS anyAliasName from yourTableName;

首先我们创建一个表 −

mysql> create table DemoTable695 (
   FirstName varchar(100)
);
Query OK, 0 rows affected (0.72 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable695 values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable695 values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('Mike');
Query OK, 1 row affected (0.16 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable695;

这将产生以下输出 -

+-----------+
| FirstName |
+-----------+
| Chris     |
| Robert    |
| David     |
| Mike      |
+-----------+
4 rows in set (0.00 sec)

以下是在 MySQL 中将 count(*) 视为变量的查询 −

mysql> select count(*) AS TOTAL_NO_OF_RECORDS from DemoTable695 ;

这将产生以下输出 -

+---------------------+
| TOTAL_NO_OF_RECORDS |
+---------------------+
| 4                   |
+---------------------+
1 row in set (0.02 sec)

相关文章


有用资源