美文网首页SpringBoot极简教程 · Spring Boot
Mysql 查询结果新增一列递增序列

Mysql 查询结果新增一列递增序列

作者: LssTechnology | 来源:发表于2019-04-13 21:35 被阅读1次
前言
有时候会遇到mysql查询的需求,需要在查询结果集新增一列序号,依次递增,当然这种实现有很简单的方案,直接用结果集for循环添加一个字段即可实现,本文讲的是通过sql查询直接实现。
1、新建一张auto 表
1.png
如果我们想筛选出level为3的字段,可写如下sql
select * from auto where level = 3;
结果如下
2.png
2、此时我们想再多加一列为序号列,让序号递增

修改sql如下
select (@xh := @xh + 1) as xh, a.* from (select * from auto where level = 3) a, (select @xh := 0) x;
结果如下

3.png
此时发现,结果集中新增了xh列,一次递增,实现了需求
3、语句解析
:= 在mysql中是赋值操作,@xh 在mysql是变量,(@xh := @xh + 1) as xh 意思相当于java中的 a = a + 1, 后面的(select @xh := 0) x 相当java中的a = 0,最后执行整条sql,mysql先执行from后的语句,此时(select * from auto where level = 3) a会产生一张虚表,(select @xh := 0) x;会将@xh变量赋值为0,最后执行from前面的语句,就出现上述结果
附上mysql查询语句时,关键字顺序和执行查询时顺序
关键字顺序
select
from 
join 
on 
where  
group by  
having  
union  
order by  
limit
查询时执行顺序
from
on
join
where
group by
having
select
distinct
union
order by
limit
希望对你有所帮助,如有不对,欢迎指正

相关文章

网友评论

    本文标题:Mysql 查询结果新增一列递增序列

    本文链接:https://www.haomeiwen.com/subject/izarwqtx.html