Detect future duplicate values while iterating through MySQL results in PHP

后端 未结 3 805
我在风中等你
我在风中等你 2020-12-21 11:03

I am trying to calculate a ranking of a team in an ordered MySQL result set, and the issue I\'m having is detecting ties for the first team to show up with the tied

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 11:23

    This question has been answered here.

    The query:

    SELECT a.team_id, a.wins, count(*) instances
    FROM
        (SELECT
            s1.team_id,
            sum(s1.score>s2.score) wins
        FROM scoreboard s1
            LEFT JOIN scoreboard s2
                ON s1.year=s2.year
                AND s1.week=s2.week
                AND s1.playoffs=s2.playoffs
                AND s1.game_id=s2.game_id
                AND s1.location<>s2.location
        GROUP BY s1.team_id) AS a
        LEFT JOIN
            (SELECT
                sum(s1.score>s2.score) wins
            FROM scoreboard s1
                LEFT JOIN scoreboard s2
                    ON s1.year=s2.year
                    AND s1.week=s2.week
                    AND s1.playoffs=s2.playoffs
                    AND s1.game_id=s2.game_id
                    AND s1.location<>s2.location
            GROUP BY s1.team_id) AS b
                ON a.wins = b.wins
    GROUP BY a.team_id, b.wins
    ORDER BY a.wins DESC;
    

    This gives the output...

    =================================
    |team_id   | wins    |instances |
    =================================
    |10        | 44      |1         |
    |2         | 42      |3         | //tie
    |9         | 42      |3         | //tie
    |5         | 42      |3         | //tie
    |3         | 41      |1         |
    |11        | 40      |1         |
    |...       |         |          |
    =================================
    

    Then, in PHP, I'll be able to detect all ties by checking when $row['instances'] > 1.

提交回复
热议问题