MySQL – How to Order by One Column Inside Another Column

MySQLorder-by

I've a MySQL table that looks like the following:

http://sqlfiddle.com/#!2/ca67ac/1

I use it to build a grid where i put my content. The resultant is this:

enter image description here

I've to render every row separatelly but, inside every row, render it's content by column.
So, for this task i need to get the rows in this order: 1, 2, 3, 4, 6, 5, 7.

column number 6 must come before 5 because it's first in the column order inside that row from left to right.

Is there any sorting method that i can use to achieve that? Order by row but order by column inside that order.

Best Answer

I've solved it by doing the following:

SELECT nWidth, nHeight, nColumn, 
(SELECT MAX(t.nRow + (t.nHeigth - 1)) FROM test t WHERE t.nRow = tp.nRow 
GROUP BY t.nRow LIMIT 1) AS nRow
FROM test tp ORDER BY nRow, tp.nColumn

This will get the max from the row number plus it's heigth minus 1. So, if we have a row that has a cell with height equal or higher than 2, all its cells are going to be in the same row. So, inside that row, we order by Column.

Hope this helps someone.