I have a table with the following (simplified) structure:
INT id,
INT type,
INT sort
What I need is a SELECT that sorts my data in a way, so that:
- all rows of the same type are in sequency, sorted ascendingly by
sortinternally, and - all “blocks” of one type are sorted by their minimum
sort.
Example:
If the table looks like this:
| id | type | sort |
| 1 | 1 | 3 |
| 2 | 3 | 5 |
| 3 | 3 | 1 |
| 4 | 2 | 4 |
| 5 | 1 | 2 |
| 6 | 2 | 6 |
The query should sort the result like this:
| id | type | sort |
| 3 | 3 | 1 |
| 2 | 3 | 5 |
| 5 | 1 | 2 |
| 1 | 1 | 3 |
| 4 | 2 | 4 |
| 6 | 2 | 6 |
I hope this makes it clear enough.
Looks to me, as this should be a very common requirement, but I didn’t find any examples close enough to be able to transfer it to my use case on my own. I suppose I can’t avoid at least one subquery, but I didn’t figure it out on my own.
Any help is appreciated, thanks in advance.
By the way: I’m going to use this query with CakePHP 2.1, so if you know of a comfortable way to do it with Cake, please let me know.
This is simpler than it initially sounds. I believe the following should do the trick:
For best (fastest) results, you’re probably going to want an index on (
type,sort).You want an additional sort by
a.type(instead of (b.min,a.sort)), in case there are two groups with the samesortvalue (would result in mixed rows). If there are no duplicate values, you can remove it.