最近有个需求,要在mysql的select查询结果中增加一个自增列,实现方法如下:

两句查完:

set @rownum=0;
select (@rownum:=@rownum+1),colname from [tablename or (subquery) a];

一句查完:

select @rownum:=@rownum+1,colnum from (select @rownum:=0) a,[tablename or (subquery) b];

示例:

mysql> select @rownum:=@rownum+1 as 'index', name, age from (select @rownum:=0) a, stu;
+-------+-------+------+
| index | name | age |
+-------+-------+------+
|  1  | zhang |  30 |
|  2  | wang  |  48 |
+-------+-------+------+
2 rows in set (0.00 sec)