MySQL Query: Order childs after their parents
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:
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...
精彩评论