求一个分组后排序显示的sql

netchengjp 2018-01-14 12:08:08


catid 为上一级栏目的编号
jb 为级别
listorder 为排序字段

上面的图如何得出先分组,然后按照listorder排序的如下结果:

id xmname catid jb listorder
4 b 0 1 1
5 b1 4 2 1
6 b2 4 2 2
1 a 0 1 2
2 a1 1 2 1
10 a2 1 2 2
11 a3 1 2 3



...全文
598 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
rucypli 2018-01-15
  • 打赏
  • 举报
回复
select * from tb order by left(xmname,1) desc,xmname
zjcxc 2018-01-15
  • 打赏
  • 举报
回复

select id, name, catid, listorder
from(
	select a.*,
		@v:=if(@g=a.id,
			( select concat_ws(',', aa.id, aa.catid, aa.listorder) from tb aa where aa.id=@id),
			concat_ws(',', a.id, a.catid, a.listorder)
			) as _v,
		@po:=concat(lpad(substring_index(@v, ',', -1), 4, '0'), if(@g=a.id,@po, '')) as _po,
		@id:=substring_index(substring_index(@v, ',', 2), ',', -1) as _id,
		@g:=a.id
	from( select a.* from tb a, tb b order by a.id )a,
		( select @po:='', @v:=null, @g:=null, @id:=null ) x
)id
where id._id = 0
order by _po

56,675

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧