I have a field number
of type varchar
. Even though it is of type varchar
, it stores integer values with optional leading zeros. A sort orders them lexicographically ("42"
comes before "9"
). How can I order by numeric values ("9"
to come before "42"
)?
Currently I use the query:
SELECT * FROM table ORDER BY number ASC
12条答案
按热度按时间sxissh061#
Try this
mqkwyuun2#
There are a few ways to do this:
00100
intact with the leading zeros.insert
/update
trigger to ensure it's set correctly whenever the string column changes.Since the vast majority of databases are read far more often than written, this third option above amortises the cost of the calculation (done at
insert
/update
) over all selects. Your selects will be blindingly fast since they use the numeric column to order (and no per-row functions).Your inserts and updates will be slower but that's the price you pay and, to be honest, it's well worth paying.
The use of the trigger maintains the ACID properties of the table since the two columns are kept in step. And it's a well-known idiom that you can usually trade off space for time in most performance optimisations.
We've used this "trick" in many situations, such as storing lower-cased versions of surnames alongside the originals (instead of using something like
tolower
), lengths of identifying strings to find all users with 7-character ones (instead of usinglen
) and so on.Keep in mind that it's okay to revert from third normal form for performance provided you understand (and mitigate) the consequences.
nxagd54h3#
Actually i've found something interesting:
This allows you to order the field like:
92dk7w1h4#
yfjy0ee75#
Trick I just learned. Add '+0' to the varchar field order clause:
I now see this answer above. I am wondering if this is typecasting the field and an integer. I have not compared performance. Working great.
llycmphe6#
For a table with values like Er353, ER 280, ER 30, ER36 default sort will give ER280 ER30 ER353 ER36
the results will be in this order ER30 ER36 ER280 ER353
t0ybt7op7#
you can get order by according to your requirement my using following sql query
uttx8gqw8#
given a column
username
containingVARCHAR
's like these:one could do:
it is not cheap, but does the job.
wgmfuz8q9#
Should display what you want it to display.. looks like you're sorting it by
id
ornumber
is not defined asinteger
at the moment.yduiuuwa10#
MySQL ORDER BY Sorting alphanumeric on correct order
example:
output:
3zwtqj6y11#
Another option to keep numerics at a top, then order by alpha.
pdkcd3nj12#
Rough and ready: order by 1*field_name