如何在 MySQL 中添加一个将行数作为序列号进行计数的新列?
mysqlmysqli database
要添加一个将行数作为序列号进行计数的新列,您可以在 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)