要添加将行数计为序列号的新列,可以在select语句中使用global变量。
让我们创建一个表。创建表的查询如下:mysql> create table addColumnToCountAsSerialNumber
-> (
-> Id int,
-> Name varchar(20),
-> Age int,
-> Salary int
-> );
使用insert命令在表中插入一些记录。查询如下:mysql> insert into addColumnToCountAsSerialNumber values(10,'John',23,8576);
mysql> insert into addColumnToCountAsSerialNumber values(12,'Carol',21,4686);
mysql> insert into addColumnToCountAsSerialNumber values(9,'Mike',22,38585);
mysql> insert into addColumnToCountAsSerialNumber values(15,'Sam',25,38586);
mysql> insert into addColumnToCountAsSerialNumber values(20,'Bob',26,43544);
mysql> insert into addColumnToCountAsSerialNumber values(39,'Larry',29,485886);
使用select语句显示表中的所有记录。查询如下:mysql> select *from addColumnToCountAsSerialNumber ;
以下是输出:+------+-------+------+--------+
| Id | Name | Age | Salary |
+------+-------+------+--------+
| 10 | John | 23 | 8576 |
| 12 | Carol | 21 | 4686 |
| 9 | Mike | 22 | 38585 |
| 15 | Sam | 25 | 38586 |
| 20 | Bob | 26 | 43544 |
| 39 | Larry | 29 | 485886 |
+------+-------+------+--------+
6 rows in set (0.00 sec)
以下是将每行计数为序列号的查询:mysql> select @globalVar:=@globalVar+1 RowCount,tblColumns.*
-> from (select @globalVar:=0) initializeGlobalVariable,addColumnToCountAsSerialNumber tblColumns;
以下是在新列“ RowCount”中显示计数的输出:+----------+------+-------+------+--------+
| RowCount | Id | Name | Age | Salary |
+----------+------+-------+------+--------+
| 1 | 10 | John | 23 | 8576 |
| 2 | 12 | Carol | 21 | 4686 |
| 3 | 9 | Mike | 22 | 38585 |
| 4 | 15 | Sam | 25 | 38586 |
| 5 | 20 | Bob | 26 | 43544 |
| 6 | 39 | Larry | 29 | 485886 |
+----------+------+-------+------+--------+
6 rows in set (0.06 sec)