How to order by certain part of a string?
How to order by certain part of a string, assuming i have column codes
which has values of the following 开发者_如何学运维format: LLL_NNN, example dGd_542. How can i order by the second part of the string which is numerical?
You should be able to just extract substring from your code.
order by SUBSTRING(codes, 4) asc
use the SUBSTRING
function
SELECT * FROM tablename
ORDER BY SUBSTRING(codes FROM 4)
On very large tables this can lead to performance issues.
(First the obligatory comment on database structure)
It appears the you have two meaningful values encoded into the single column codes
. If at all possible you should refactor your database so those are separate columns. The sorting problem then goes away.
(Now the answer using the existing database structure)
You can use an expression and order by that expression:
SELECT c1, c2, c3, SUBSTRING_INDEX(codes, '_', 2) as code_value
FROM table ORDER BY code_value
If I understood, this can solve your problem...
select substring( field, 5, 7) as field2 from db.table order by field;
精彩评论