Search code examples
mysqlminimum

minimum between columns in mysql with least(), give unpredicted result


In a view statement i try to add a column which gives me the minimum between between the user_value and friend_value column. the query doesn't give a error and gives me the desired result for 90% of the rows. sometime i find a row with for example user_value 35 and fried_value 119 and then the relation_value 119 while this supposed to be 35....

SELECT User, friend,  user_value, friend_value,  Least(user_value,friend_value) as relation_value



+----+------+--------+------------+--------------+----------------+
|  1 | User | friend | user_value | friend_value | relation_value |
|  2 | 1    | 2      | 35         | 50           | 35             |
|  3 | 1    | 4      | 35         | 20,5         | 20,5           |
|  4 | 1    | 29     | 10         | 15           | 10             |
|  5 | 1    | 30     | 35         | 37,5         | 35             |
|  6 | 1    | 31     | 35         | 40           | 35             |
|  7 | 1    | 32     | 35         | 10           | 10             |
|  8 | 1    | 33     | 35         | 16,66666666  | 16,66666666    |
|  9 | 1    | 34     | 35         | 119          | 119            |
| 10 | 1    | 35     | 35         | 8            | 35             |
| 11 | 1    | 36     | 35         | 120          | 120            |
+----+------+--------+------------+--------------+----------------+

i hope somebody can tell me where i can find the root of this problem...


Solution

  • As I stare at your results, there is another possibility besides the "indeterminate" row problem. That possibility is that your query is working, but the values are stored as characters rather than numbers. That would explain the results. You can fix this by converting the values to numbers. Here is an easy way:

    SELECT User, friend,  user_value, friend_value,
           Least(user_value + 0, friend_value + 0) as relation_value
    

    Note that if the value contains a string that does not start with digits, it will have the value of 0.

    Moral of the story: If you want to store numbers, use numeric data types, not character strings.