在 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