문제

I recently built an online game that is still in developing mode. Using mysqli I query a table to get the current user's rank. This is based on position within table, ordered by score.

The problem is I have two separate rank positions to get and I currently do this in two separate queries, could someone point me in the right direction as to combine these.

Current setup

$sql="SELECT * from 
(
SELECT mode1_score, name, id, @rank := @rank + 1 as rank 
FROM users, (SELECT @rank := 0) r
ORDER BY mode1_score DESC
) users
order by mode1_score DESC";

//code to output rank here for game mode 1

// new query
$sql="SELECT * from 
(
SELECT mode2_score, name, id, @rank := @rank + 1 as rank 
FROM users, (SELECT @rank := 0) r
ORDER BY mode2_score DESC
) users
order by mode2_score DESC";

//code to output rank here for game mode 2

Data Structure

Table name = users

id       |  name  |  mode1_score  |  mode2_score
-------------------------------------------------
1233345     foo         0              1200
3454535     boo        847             1143
2344443     doo        1127            687
도움이 되었습니까?

해결책

The only thing I can think of is doing something like the below query. What I am doing is setting a constant that identifies the mode score, then I wrap that query and order by the mode constant first and the actual score second. Then in your code you know that ModeConst of 1 is for the mode1_score and a ModeConst of 2 is for the mode2_score.

The mode_score will be ordered like you want since the constant is ordered first.

SELECT * FROM 
(
  SELECT 1 AS ModeConst, mode1_score AS ModeScore, name, id, @r := @r + 1 as rank 
  FROM users, (SELECT @r := 0) r
  ORDER BY mode1_score DESC 
) a
UNION 
SELECT * FROM 
(
  SELECT 2 AS ModeConst, mode2_score AS ModeScore, name, id, @s := @s + 1 as rank 
  FROM users, (SELECT @s := 0) s
  ORDER BY mode2_score DESC
) b
ORDER BY 1, 2 DESC

Which would produce the following results:

enter image description here

Your code would handle whatever you have for:

//code to output rank here for game mode 1

Then once the first ModeConst with a value of 2 is found you would start and finish executing whatever you have for:

//code to output rank here for game mode 2

SQL Fiddle Sample

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top