mysql给查询结果额外添加自增列

时间:2022-10-14 14:07:48
1、模板如下:
SELECT (@rownum:=@rownum+1) 自增序号别名, 结果集字段
FROM 结果集, (SELECT @rownum:=0) AS 任意别名

示例如下:
SELECT @rownum:=@rownum+1 AS rownum, aliaA.*
FROM (
select username,age from test
) aliaA, (SELECT @rownum:=0) aliaB
#此处aliaA和aliaB两个别名必须有
不然就会报错
"Every derived table must have its own alias(每一个派生出来的表都必须有一个自己的别名)"

2、上述语句的效果等同于下述语句
set @rownum:=0;
Select (@rownum:=@rownum+1) as rownum, 结果集aliaA.* from 结果集

3、上述的方法同样适用于分页查询:
Select (@rownum:=@rownum+1) as rownum, aliaA.*
FROM 结果集 aliaA,(Select @rownum:=0) aliaB
order by aliaA.id desc
limit 0, 10;

Set @rownum:=0;
Select (@rownum:=@rownum+1) as rownum, aliaA.*
FROM 结果集 aliaA
order by aliaA.id desc
limit 0, 10;

4、示例
示例1直接输出
select @rownum:=@rownum+1 AS num1, username,age FROM (
select username,age from test
) A,(SELECT @rownum:=0) B;
示例2使用concat拼接
select concat('hello--',@rownum:=@rownum+1,'|',username,'|',age) FROM (
select username,age from test
) A,(SELECT @rownum:=0) B;
生成结果:
hello--1|zhangsan|23
hello--2|lisi|24