开发者

MySQL Query: Order childs after their parents

开发者 https://www.devze.com 2023-04-02 01:13 出处:网络
I have a table with: Can I with a single query organize it to sh开发者_JAVA技巧ow: Thank you.Yes, you could do this bastardization:

I have a table with:

MySQL Query: Order childs after their parents

Can I with a single query organize it to sh开发者_JAVA技巧ow:

MySQL Query: Order childs after their parents

Thank you.


Yes, you could do this bastardization:

ORDER BY CASE parentid WHEN 0 THEN id ELSE parentid END ASC, id ASC

I say it's a bastardization because it requires a computation for every single row. It will not be performant. The better way to solve this problem would be to use a better datamodel. Instead of storing just parent ids, you can also store using a Nested Set Model. So basically your datamodel would look like:

id | parentid | name   | left | right
1  | 0        | Peter  | 1    | 4
2  | 0        | Marcus | 5    | 8
3  | 1        | Monica | 2    | 3 
4  | 2        | Sergei | 6    | 7

Now, with that, your order would be reduced to:

ORDER BY `left` ASC

Which would do the exact same thing. Give that nested set article a read. There are better ways to solve the problem than just parentid if you need to get data out either filtered or sorted...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号