mysql select结果中增加自增列

admin 阅读:140 2024-03-02

最近有个需求,要在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)
 
声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!