1

I have a table with a list of ranks for a character, each associated with a numeric value (xp). Higher the rank is more XP is needed. I would like to know the easiest way to construct a query to find to which rank the character belongs. The idea is to use it is a subquery, so when selecting the character

SELECT name, xp FROM characters

I would be able to get the character rank based on the amount of XP. If I use two columns in the ranks table for min and max XP needed it is easy:

SELECT
  name, xp
  (SELECT rank FROM ranks WHERE xp BETWEEN xp_min AND xp_max) as rank
FROM characters

but I'd like to have it done with just one column for the lower boundary of rank

UPDATE: looks like INTERVAL here is a red herring, keeping it for search purposes

I could use INTERVAL() function (MySQL Documentation) for this if I construct the query programatically:

SELECT INTERVAL(character_xp, rank1, rank2, rank3, rank4)

But is there a way to use a sub-query to achieve this? The following does not work

SELECT INTERVAL(character_xp, (SELECT rank FROM ranks ORDER by rank))

And neither does this:

SELECT INTERVAL(character_xp, (SELECT GROUP_CONCAT(rank ORDER BY rank) FROM ranks));

Any advice?

1

1 Answer 1

1

Does this do what you need? Here, xp is the "goal xp" for that rank. This query returns the rank that corresponds to the current character xp value.

Example:

character xp : 12000

name     | rank | xp
Level 1    1      10000
Level 2    2      20000
Level 3    3      40000

Query:

SELECT
    name,
    rank,
    xp,
    (<character xp here> - xp) AS diff
FROM ranks
HAVING diff > 0
ORDER BY diff ASC
LIMIT 1

Replacing <character xp here> with 12000, the result is:

name     | rank | xp     | diff
Level 1    1      10000    2000

So, the character has reached rank 1, and is 2000 xp over the goal for rank 1.

6
  • Unfortunately in this way it cannot be used as a subquery which was my original goal, so I will wait a little for another answer before accepting yours May 26, 2012 at 19:50
  • Are you required to use INTERVAL with a subquery? May 26, 2012 at 19:52
  • No, anything which would work in subquery would do. Your example works but has two columns so I cannot use it May 26, 2012 at 19:58
  • Can you add to your question why you require a subquery and an example of how you would use it? Or are you trying to use it in the INTERVAL function (which you cannot)? May 26, 2012 at 20:00
  • Tried to expand the question to give more background May 26, 2012 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.