Question

i have the table 'points_level' with :

id | description | level
--------------------------
1  | noob        | 0
2  | rookie      | 50
3  | The boss    | 100

i need to build a function that return the id of the level giving points as integer for example :

select calc_level(12)
result: 1

select calc_level(90)
result: 2

select calc_level(300)
result: 3

select calc_level(100)
result: 3

select calc_level(-50)
result: 1

i need to add some level in the points_level table (in the near future) so i shuldn't calculate the results via some simple "CASE WHEN" i think about a "CASE WHEN" in a for loop, i found some example for SSQL but nothing for MYSQL and i don't know the MYSQL SYNTAX for create this kind of function :(

somebody can help me ?

Thanks

Was it helpful?

Solution

The algorithm is relatively simple - you need the id where the points supplied is greater than or equal to the level:

SELECT id
FROM points_level
WHERE 
  (<points_input> >= level)
  -- For negative input, return the lowest level
  OR (<points_input> < 0 AND level <= 0)
ORDER BY level DESC LIMIT 1

http://sqlfiddle.com/#!2/07601/4

Review the MySQL CREATE FUNCTION syntax for the proper way to wrap it in a function (if you feel you really need that).

CREATE FUNCTION calc_level (in_points INT)
RETURNS INT
BEGIN
    DECLARE id_out INT;
    SET id_out = (
      SELECT id
      FROM points_level
      WHERE
        in_points >= level 
        OR (in_points < 0 AND level <= 0)
      ORDER BY level DESC LIMIT 1
    );
    RETURN id_out;
END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top