我正在尝试创建一个mysql查询,根据他们的分数对MMA战士进行排名,以及他们是否专业,以及他们的体重等级,共同创建一个战士师。我有一张包含所有战士的表,其中包含他们的体重,状态(专业或业余)以及其他一些列。我还有一张表格,其中包含根据所有战斗计算出的分数。记录需要按分部和分数排序,但我只能通过分部查询我的查询:
INSERT INTO fa_rankings (fighter_id, rank, division)
SELECT
fa_scores.fighter_id,
@r := CASE WHEN @div <> f_division THEN 1 ELSE @r+1 END as f_rank,
@div := f_division
FROM
(SELECT @div := NULL) d,
(SELECT @r := 0) r,
fa_scores
JOIN (SELECT fa_fighters.fighter_id,
CONCAT(
IF(status = 'professional', 'a', 'b'),
CASE
WHEN weight < 126 THEN 0
WHEN weight BETWEEN 126 AND 135 THEN 1
WHEN weight BETWEEN 136 AND 145 THEN 2
WHEN weight BETWEEN 146 AND 155 THEN 3
WHEN weight BETWEEN 156 AND 170 THEN 4
WHEN weight BETWEEN 171 AND 185 THEN 5
WHEN weight BETWEEN 186 AND 205 THEN 6
WHEN weight BETWEEN 206 AND 265 THEN 7
ELSE 8 END) as f_division
FROM fa_fighters
ORDER BY f_division ASC) as fighters using (fighter_id)
ORDER BY score DESC
我猜这与最后一个order by语句的位置有关,但我无法弄清楚在哪里放置它,因为它在加入的查询中不起作用。现在,此查询生成以下内容:
Rankings Table Compared with Scores
+------------+------+----------+ +-------+
| fighter_id | rank | division | | score |
+------------+------+----------+ +-------+
| 131 | 1 | a1 | | 0 |
| 23 | 2 | a1 | | 34 |
| 332 | 3 | a1 | | 4 |
| 1233 | 1 | a2 | | 0 |
| 643 | 2 | a2 | | 44 |
+------------+------+----------+ +-------+
编辑:我之前的查询没有使用过连接,但是只根据战斗机是否专业进行分组,并且该查询确实正确应用了排名,所以我怀疑它与连接有关。< / p>
编辑:这是我的选择
的输出SELECT * ,
(SELECT CONCAT_WS( ' ', f_name, l_name ) FROM fa_fighters WHERE fa_fighters.fighter_id = fa_rankings.fighter_id)
AS name,
(SELECT score FROM fa_scores WHERE fa_scores.fighter_id = fa_rankings.fighter_id)
AS score
FROM `fa_rankings`
WHERE 1
ORDER BY division, rank ASC
LIMIT 0 , 30
编辑:它是按分数排序记录,但是在错误的位置;它在确定等级后按分数对它们进行排序,以便原始表按分数排序,但战斗机没有与它们相关联的正确等级。我需要查询在运行排名计数器之前按分数对记录进行排序,并确定每个战士等级。这是一个问题,当执行查询时正在应用ORDER BY时,我只是不知道放在哪里。
答案 0 :(得分:1)
我发现将“ORDER BY得分DESC”移动到连接的子查询中会产生正确的结果:
INSERT INTO fa_rankings (fighter_id, rank, division)
SELECT
fa_scores.fighter_id,
@r := CASE WHEN @div <> f_division THEN 1 ELSE @r+1 END as f_rank,
@div := f_division
FROM
(SELECT @div := NULL) d,
(SELECT @r := 0) r,
fa_scores
JOIN (SELECT fa_fighters.fighter_id,
CONCAT(
IF(status = 'professional', 'a', 'b'),
CASE
WHEN weight < 126 THEN 0
WHEN weight BETWEEN 126 AND 135 THEN '1'
WHEN weight BETWEEN 136 AND 145 THEN '2'
WHEN weight BETWEEN 146 AND 155 THEN '3'
WHEN weight BETWEEN 156 AND 170 THEN '4'
WHEN weight BETWEEN 171 AND 185 THEN '5'
WHEN weight BETWEEN 186 AND 205 THEN '6'
WHEN weight BETWEEN 206 AND 265 THEN '7'
ELSE '8' END) as f_division
FROM fa_fighters
ORDER BY
f_division ASC,
#the score column in the form of a subquery
(select score from fa_scores where fa_scores.fighter_id = fa_fighters.fighter_id) DESC)
as fighters using (fighter_id)
答案 1 :(得分:0)
看起来你的表TABLE有一个分区索引,这就是为什么输出看起来像那样。
如果您在进行查询时没有指定order by
,那么该表将不会有任何订单,即使索引您将有某种订单,但它不是100%的准确性巨大的桌子。
恢复,在您的查询中,您有一个带有顺序和连接的INSERT,但这并不意味着当您创建select.....
时,输出将与输入的顺序相同。我的建议总是指定ORDER BY
并且有一个独特或主要的键(至少其中一个)。