MySQL SELECT和ORDER BY

时间:2013-07-21 12:13:28

标签: mysql final

关于:MySQL ORDER BY or GROUP BY,我做得更复杂。我有一个id_competitor,在不同的路线上有各种分数。

id_competitor   score    id_route
1                WIN        2
2                WIN        2
3                50+        2
4                50+        2
1                70         1
2                70+        1
3                70         1
4                WIN        1

这是表“路线”

id       name
1      semi-final
2        final

结果应按以下顺序排列:

id_competitor
2
1
4
3

因为他们在决赛中扳平比分并打破僵局所以我们看看半决赛

1 个答案:

答案 0 :(得分:0)

考虑以下数据集......

DROP TABLE IF EXISTS results;

CREATE TABLE results
(id_competitor   INT NOT NULL
,score    INT NOT NULL
,id_route INT NOT NULL
,PRIMARY KEY(id_competitor,id_route)
);

INSERT INTO results VALUES
(1,100,2),
(2,100,2),
(3,60,2),
(4 ,60,2),
(1,70,1),
(2,80,1),
(3,70,1),
(4,100,1);

SELECT * FROM results;
+---------------+-------+----------+
| id_competitor | score | id_route |
+---------------+-------+----------+
|             1 |    70 |        1 |
|             1 |   100 |        2 |
|             2 |    80 |        1 |
|             2 |   100 |        2 |
|             3 |    70 |        1 |
|             3 |    60 |        2 |
|             4 |   100 |        1 |
|             4 |    60 |        2 |
+---------------+-------+----------+

我们希望通过id_route = 2的最高分来安排竞争对手。如果分数相关,则应考虑id_route 1的结果。正确的顺序应该是2,1,4,3。

中级解决方案......

SELECT * 
  FROM results x 
  JOIN results y 
    ON y.id_competitor = x.id_competitor 
   AND y.id_route = 1 
 WHERE x.id_route = 2;
+---------------+-------+----------+---------------+-------+----------+
| id_competitor | score | id_route | id_competitor | score | id_route |
+---------------+-------+----------+---------------+-------+----------+
|             1 |   100 |        2 |             1 |    70 |        1 |
|             2 |   100 |        2 |             2 |    80 |        1 |
|             3 |    60 |        2 |             3 |    70 |        1 |
|             4 |    60 |        2 |             4 |   100 |        1 |
+---------------+-------+----------+---------------+-------+----------+

完整的解决方案......

SELECT x.id_competitor
     , x.score final_score
     , y.score semi_final_score 
  FROM results x 
  JOIN results y 
    ON y.id_competitor = x.id_competitor 
   AND y.id_route = 1 
 WHERE x.id_route = 2 
 ORDER 
    BY final_score DESC
     , semi_final_score DESC;
+---------------+-------------+------------------+
| id_competitor | final_score | semi_final_score |
+---------------+-------------+------------------+
|             2 |         100 |               80 |
|             1 |         100 |               70 |
|             4 |          60 |              100 |
|             3 |          60 |               70 |
+---------------+-------------+------------------+