mysql 分组排序,pid为 n 的行 跟在 id 为 n 的行后面,分多级

mysql 分组排序,pid为 n 的行 跟在 id 为 n 的行后面,分多级,第1张

假设表结构是

ordertest(id,pid,name)

id是唯一的,pid有重复且只取自id中存在的数值

实现代码如下:

select t.id,t.pid,t.`name` from 

(select a.*,b.id as f1,

(select id from ordertest where id=a.pid 

and id<a.id limit 1) f2,

(select max(id) from ordertest where 

pid=a.pid and id<a.id having count(1)>1) as f3 

from ordertest a left join 

(select a.id from ordertest a where exists(

select 1 from ordertest b where b.id<>a.id 

and b.pid=a.id)) b on a.id= b.id) t 

order by 

case when f2 is null then t.id 

else ifnull(f1,

case when f3 is null then f2 else t.id end) end,

case when f2 is null then 0 

else if((f1 is not null) or (f3 is not null),0,1) 

end,t.id

运行效果如下图

题主的这个排序需求,用SQL来解决,其难度的确比较大,不过经过特殊的排序安排还是可以解决的。请参考下列语句:

这里假设表名为OrderTest(id,pid,name) id是主键具有唯一性

select t.id,t.pid,t.`name` from 

(select a.*,

(select id from OrderTest where id=a.pid and 

id<>a.id limit 1) as p

from OrderTest a) t 

order by 

IFNULL(t.p,t.id),

case when t.p is null then 0 else 1 end,t.id

下面是实验截图

使用别名

SELECT COUNT(*) 

FROM `category` `A` LEFT JOIN `category` `B`

ON A.`pid` = B.`id`


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/8401899.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-16
下一篇 2023-04-16

发表评论

登录后才能评论

评论列表(0条)

保存