Home >Database >Mysql Tutorial >How Can I Sort a MySQL Column Containing 'name-number' Strings Numerically?
Convert Partial Non-Numeric Text into Numbers for MySQL Query Sorting
In MySQL, sorting varchar columns based on embedded numeric values can be challenging. This question addresses a practical scenario where a column contains identifiers in the format "name-number" and needs to be sorted based on the numerical component.
Problem:
The column contains text in the format "name-number," with the number component embedded within the text. Sorting the column using the default character order results in an inaccurate sequence due to the character comparison.
Solution:
To resolve this, it is necessary to convert the non-numeric text into numbers before sorting. The following query can accomplish this:
SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num FROM table ORDER BY num;
Explanation:
Additional Considerations:
The above is the detailed content of How Can I Sort a MySQL Column Containing 'name-number' Strings Numerically?. For more information, please follow other related articles on the PHP Chinese website!