结合2个独立的复杂查询

时间:2014-05-14 19:25:29

标签: sql mysqli subquery union

我最近制作了一款仍处于开发模式的在线游戏。使用mysqli我查询表以获取当前用户的排名。这是基于表格中的位置,按得分排序。

问题是我有两个不同的排名位置,我目前在两个单独的查询中执行此操作,有人可以指出我正确的方向,以结合这些。

当前设置

$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

数据结构

表名= users

id       |  name  |  mode1_score  |  mode2_score
-------------------------------------------------
1233345     foo         0              1200
3454535     boo        847             1143
2344443     doo        1127            687

1 个答案:

答案 0 :(得分:1)

我唯一能想到的就是做类似下面的查询。我正在做的是设置一个标识模式分数的常量,然后我将该查询和顺序首先按模式常量和实际分数排序。然后,在您的代码中,您知道ModeConst的{​​{1}}适用于1mode1_score ModeConst适用于2

mode2_score将按照您的要求进行排序,因为首先订购常量。

mode_score

哪会产生以下结果:

enter image description here

您的代码可以处理您拥有的任何内容:

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

然后,一旦找到值//code to output rank here for game mode 1 的第一个ModeConst,您就可以开始并完成执行任何操作:

2

SQL Fiddle Sample