如何在MySQL中添加一个新列,用于计数行数作为序号?
要添加一个新列来计数行数作为序号,你可以在SELECT语句中使用全局变量。
让我们创建一个表。创建表的查询如下所示
mysql> create table addColumnToCountAsSerialNumber -> ( -> Id int, -> Name varchar(20), -> Age int, -> Salary int -> ); Query OK, 0 rows affected (0.80 sec)
使用INSERT命令在表中插入一些记录。查询如下所示
mysql> insert into addColumnToCountAsSerialNumber values(10,'John',23,8576); Query OK, 1 row affected (0.10 sec) mysql> insert into addColumnToCountAsSerialNumber values(12,'Carol',21,4686); Query OK, 1 row affected (0.14 sec) mysql> insert into addColumnToCountAsSerialNumber values(9,'Mike',22,38585); Query OK, 1 row affected (0.11 sec) mysql> insert into addColumnToCountAsSerialNumber values(15,'Sam',25,38586); Query OK, 1 row affected (0.16 sec) mysql> insert into addColumnToCountAsSerialNumber values(20,'Bob',26,43544); Query OK, 1 row affected (0.17 sec) mysql> insert into addColumnToCountAsSerialNumber values(39,'Larry',29,485886); Query OK, 1 row affected (0.16 sec)
使用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)
广告