I’ve stored a X, Y
coordinate system in mysql where x-axis values are from A, B....AA, AB...
and so forth, just like columns are named in Excel. Y-axis values are from 1 to 100.
I can’t figure out how to select all x-axis values that are "lower" than i.e. ‘AZ
‘. My query result should be A, B, C...AA, AB...AZ
values, but mysql considers B to be greater than AA.
SELECT x_axis, y_axis
FROM coordinates
WHERE x_axis<'AZ'
ORDER BY length(substring_index(x_axis, ' ', 1)),
substring_index(x_axis, ' ', 1);
Hope my question makes sense.
Thanks
I managed to make the sorting correct, but I am stuck with the WHERE part and mysqls alphabetic sorting
2
Answers
String comparison in MySQL is case-sensitive, and it compares the ASCII values of the characters. Since ‘Z’ has a greater ASCII value than ‘A’, ‘AZ’ is considered greater than ‘AA’.
To solve this issue, you can use the ORDER BY clause with a custom sorting order. You can use the FIELD() function to assign a custom order to your x_axis values, then use that value in the ORDER BY clause.
If you want the solution to be more reusable you can set a user-defined variable to store the order of each x_axis value, and then use that variable in the ORDER BY clause.
Your query should be ordered by two values: length of x_axis and x_axis values.
You could try sample query here: https://onecompiler.com/mysql/3yupevx2v