MYSQL排序依赖于2行其他行IDS

时间:2017-07-23 18:38:15

标签: php mysql sql

我正在尝试创建一个允许我选择如下所示数据的查询 由角色45组织并按DESC的顺序显示其赢率。 例如champ_1 = 45和champ_2 = 36但有时候它可以是champ_1 = 36而champ_2 = 45.这样我将如何进行查询以便命令冠军45的胜率取决于其冠军或冠军2和然后组织它desc。

id      Role      Champ_1       Champ_2    Champ_1_winrate  Champ_2_winrate
---|------------|------------|-----------|-----------------|---------------
1  | 1          |     45     |     17    |       0.54      |      0.46      
2  | 1          |     67     |     45    |       0.52      |      0.48      
5  | 1          |     45     |     27    |       0.59      |      0.41     
3  | 1          |     45     |     35    |       0.29      |      0.71     
4  | 1          |     45     |     23    |       0.094     |      0.916     
6  | 1          |     80     |     45    |       0.38      |      0.62     
7  | 1          |     45     |     47    |       0.544     |      0.456     
8  | 1          |     32     |     45    |       0.78      |      0.22     

它应该显示数据:

id      Role      Champ_1       Champ_2       winrate   
---|------------|------------|-----------|-----------------|
6  | 1          |     80     |     45    |       0.62      |      
5  | 1          |     45     |     27    |       0.59      |       
7  | 1          |     45     |     47    |       0.544     |     
1  | 1          |     45     |     17    |       0.54      |            
2  | 1          |     67     |     45    |       0.48      |            
3  | 1          |     45     |     35    |       0.29      |                   
8  | 1          |     32     |     45    |       0.22      |      
4  | 1          |     45     |     23    |       0.094     |      

我已经尝试过以下代码,而且我最近的代码已经过了3个多小时了,所以有人可以帮忙。

SELECT * 
FROM Bronze_Matchups a 
WHERE (Champ_2 = 24 AND Role = 'JUNGLE') 
OR (Champ_1 = 24 AND Role = 'JUNGLE') 
ORDER BY Champ_2_winrate desc, Champ_1_winrate asc

2 个答案:

答案 0 :(得分:1)

您可以使用UNION和ORDER BY(根据需要在ORDER BY子句中添加desc或asc)

SELECT a.id, a.Role, a.Champ_1, a.Champ_2, a.Champ_2_winrate as winrate
 FROM Bronze_Matchups a 
 WHERE a.Champ_2 = 24 
 AND a.Role = 'JUNGLE'
UNION
SELECT a.id, a.Role, a.Champ_1, a.Champ_2, a.Champ_1_winrate as winrate
 FROM Bronze_Matchups a 
 WHERE a.Champ_1 = 24
 AND a.Role = 'JUNGLE'
ORDER BY winrate

答案 1 :(得分:0)

在您的订单中使用案例陈述

SELECT * 
FROM Bronze_Matchups a 
WHERE 
   (Champ_2 = 24 AND Role = 'JUNGLE') 
   OR (Champ_1 = 24 AND Role = 'JUNGLE') 
ORDER BY 
   CASE
       WHEN Champ_2 = 24 THEN Champ_2_winrate
       ELSE Champ_1_winrate
   END