In MySQL, is there a way to order my results by the length (characters) of a column?
For example:
myColumn
________________
lor
lorem
lorem ip
lorem ips
lorem ipsum
I would like to order my results by the smallest column length first, "lor", and ending in the largest column length, "lorem ipsum". This should include column lengths of 0 too.
Any suggestions gratefully received...
解决方案
You can use
ORDER BY CHAR_LENGTH( column )
Notice that CHAR_LENGTH() works for Unicode strings as well, where LENGTH() is OK for Latin but may give unexpected results with Unicode:
CHAR_LENGTH(str)
Returns the length of the string str, measured in characters. A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.