I have an entity attribute model for storing information related to users. I am also then trying to sort a particular entity which only contains numbers in decreasing order. I am running a query such as the following:
SELECT * FROM `user_meta` WHERE `key` = 'children' ORDER BY `user_meta`.`value` DESC
I had not run into problems with this query until recently when a user had 11 children and now the results look as follows
+-----+----------+-------+
| uid | key | value |
+-----+----------+-------+
| 1 | children | 5 |
| 1 | children | 3 |
| 1 | children | 3 |
| 1 | children | 2 |
| 1 | children | 11 |
| 1 | children | 1 |
+-----+----------+-------+
I have tried various different modifications of this query but have not found anything fixing this ranking problem where 5 > 11. It might be of use but both the key and value attributes are varchar(250) if that affects the sorting algorithm that MySQL uses.
This happens when your column is a
CHARtype. It compares the strings rather than the numbers.You could cast it when ordering:
Or for signed integers:
See also: Cast Functions and Operators