I’m using MySQL 5.1
table users:
id | exp
---------
5 | 5
4 | 9
table levels:
id|min_exp
----------
1 | 0
2 | 5
3 | 8
How to select user with his levels.id?
I need to join table users and levels.
This must be valid:
users.exp >= levels.min_exp
and min_exp should be lowest as it can be.
expected output:
users.id|users.exp|levels.id|levels.min_exp
5 | 5 | 2 | 5
4 | 9 | 3 | 8
If there are no gaps in level.id, you could get better performance by joining
levelstwice and avoiding aggregates:If you need the min/max experience bracket frequently, I’d recommend making the
current_level/next_leveljoin a view.Edit: It just occurred to me that this fails for users at maximum level. Depending on how you want to handle that (do users stop gaining XP at max or continue gaining it without increasing level?), you could add a dummy record above max level in
levelsor make thenext_leveljoin an outer join.