
The left table is a result of my query. And I need to sort it as the right table.
I need to order by p_id, if level >= 2. The blue box of right table is a target of order by.
Is it possible? Of course it is an example. Actual data is hundreds and really need to be sorted.
I searched a lot, but coudln’t find the same case.
edit : this table will be returned as java.util.ArrayList. If this kind of ‘order by’ is not possilbe, is it possible in java.util.ArrayList?
I’m sure it’s not possible in one query in MySQL.
In your diagram on the right, the ordering has been done in two separate steps:
Sort by id
Sort each block by p_id if level >= 2
That’s quite difficult to do in MySQL as you would need to identify the blocks and then iterate over them, sorting each block separately.
I’ve done something similar where ordering within blocks was required and then selecting from those ordered blocks. You can view that here but as I said, I think that that SQL code is horribly complicated involving 5 temporary tables. You would probably need fewer temp tables, but it would still be a very complicated procedure, quite slow and hard to maintain.
Is there any reason why you can’t just sort it as you want in code?
Trying to solve a general programming problem in MySQL when you could solve it in 1/10th of the programmer time (and probably have it perform faster as well) in Java is not a good path to follow.