问题描述
比如有这样一个查询数据的语句:select roleName,roleId from role order by roleAge;我现在想要给查询出的每一行上加一个序号,也就是说像这样一样:index roleName roleId 1 a 11 2 b 12 3 c 13 等等请问,我怎样在不在表role里增加字段的情况下,只用select语句就解决这个问题,求解答!! 问题补充:Rainbow702 写道
解决方案
SELECT (@rowNO := @rowNo+1) AS rowno,fname,fage,fsalary FROM (SELECT fname,fage,fsalary FROM t_employee ORDER BY fsalary) a ,( (SELECT @rowNo:=0) ) b;;打印结果:rownofnamefagefsalary1Stone221200.002Jane232200.883Jerry282300.804N272800.005Smith283900.006John235000.007Tina255200.368Kerry286200.009Tom258300.00注意如果用到排序,此时你必须先进行排序,把排序后的结果集作为一个续表,再次进行添加序号。通过适当修改,可以满足分页处理。SELECT (@rowNO := @rowNo+1) AS rowno,fname,fage,fsalary FROM (SELECT fname,fage,fsalary FROM t_employee ORDER BY fsalary) a ,( (SELECT @rowNo:=0) ) b LIMIT 0,5;打印结果:rownofnamefagefsalary1Stone221200.002Jane232200.883Jerry282300.804N272800.005Smith283900.00
解决方案二:
引用这个在有orderby的时候好像不行啊,得到的index会很大,不是想要的1,2,3,...啊~ 不会吧,这么邪门啊
解决方案三:
Select (@rowNum:=@rowNum+1) as index,roleName,roleIdFrom a,(Select (@rowNum :=0) ) b