sql - How can I sort A1,A2,A3,B1,B2,B3,...,AA1,AA2,AA3 in MySQL? -
i have data set looks this:
+--------+ | square | +--------+ | a1 | | a10 | | a2 | | a3 | | a4 | | a5 | | a6 | | a7 | | a8 | | a9 | | b1 | | b10 | | b2 | | b3 | | b4 | | b5 | | b6 | | b7 | | b8 | | b9 |
...
| aa1 | | aa10 | | aa2 | | aa3 | | aa4 | | aa5 | | aa6 | | aa7 | | aa8 | | aa9 | +--------+
the prefix runs a#-z#, goes aa#-zz# , continues, maximum of 2 letters (i.e. never go on zz). number suffix can length (i.e. a1,a10,a100,a1000,etc.).
how can sort these , have result set come out follows:
+--------+ | square | +--------+ | a1 | | a2 | | a3 | | a4 | | a5 | | a6 | | a7 | | a8 | | a9 | | a10 | | b1 | | b2 | | b3 | | b4 | | b5 | | b6 | | b7 | | b8 | | b9 | | b10 |
...
| aa1 | | aa2 | | aa3 | | aa4 | | aa5 | | aa6 | | aa7 | | aa8 | | aa9 | | aa10 | +--------+
you need restructure table or else have inefficient query this,
select square table1 order case when square regexp '^[a-z]{2}' 1 else 0 end asc, case when square regexp '^[a-z]{2}' left(square, 2) else left(square, 1) end asc, case when square regexp '^[a-z]{2}' cast(right(square, length(square) - 2) signed) else cast(right(square, length(square) - 1) signed) end asc
or using if
select square table1 order square regexp '^[a-z]{2}' asc, if(square regexp '^[a-z]{2}', left(square, 2), left(square, 1)), cast(if(square regexp '^[a-z]{2}', right(square, length(square) - 2), right(square, length(square) - 1)) signed)
Comments
Post a Comment