在 MySQL 查询中返回结果后生成记录的行数(序列号)?
若要生成序列号,即在 MySQL 查询中生成行数,请使用以下语法。
SELECT @yourVariableName − = @yourVariableName+1 anyAliasName, yourColumnName1,yourColumnName2,yourColumnName3,....N from yourTableName , (select @yourVariableName − = 0) as yourVariableName;
为了理解以上语法,我们来创建一个表。创建表的查询如下 −
mysql> create table tblStudentInformation -> ( -> StudentName varchar(20), -> StudentAge int, -> StudentMathMarks int -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into tblStudentInformation values('Carol',23,89);
Query OK, 1 row affected (0.18 sec)
mysql> insert into tblStudentInformation values('Bob',25,92);
Query OK, 1 row affected (0.22 sec)
mysql> insert into tblStudentInformation values('John',21,82);
Query OK, 1 row affected (0.15 sec)
mysql> insert into tblStudentInformation values('David',26,98);
Query OK, 1 row affected (0.21 sec)使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from tblStudentInformation;
输出如下。
+-------------+------------+------------------+ | StudentName | StudentAge | StudentMathMarks | +-------------+------------+------------------+ | Carol | 23 | 89 | | Bob | 25 | 92 | | John | 21 | 82 | | David | 26 | 98 | +-------------+------------+------------------+ 4 rows in set (0.00 sec)
以下是在 MySQL 查询中生成序列号的查询 −
mysql> SELECT @serialNumber − = @serialNumber+1 yourSerialNumber, -> StudentName,StudentAge,StudentMathMarks from tblStudentInformation, -> (select @serialNumber − = 0) as serialNumber;
以下输出以序列号的形式显示行号。
+------------------+-------------+------------+------------------+ | yourSerialNumber | StudentName | StudentAge | StudentMathMarks | +------------------+-------------+------------+------------------+ | 1 | Carol | 23 | 89 | | 2 | Bob | 25 | 92 | | 3 | John | 21 | 82 | | 4 | David | 26 | 98 | +------------------+-------------+------------+------------------+ 4 rows in set (0.00 sec)
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP