sql >> データベース >  >> RDS >> Mysql

MySQLSELECTおよびORDERBY

    次のデータセットを検討してください...

    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_route1の結果を考慮に入れる必要があります。正しい順序は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 |
    +---------------+-------------+------------------+
    



    1. MYSQLでアイテムを選択する方法、下のアイテムと上のアイテム

    2. InnoDBのALTERTABLE用にMySQLを最適化する

    3. PostgreSQLの日付から月の名前を取得する

    4. 0と1で構成される長い数値を格納するのに最適なデータ型