MySQL:如何让用户获得最多的胜利?

时间:2009-09-25 12:51:19

标签: sql mysql select

我有一个包含以下字段的表:id,opp1,opp2,opp1_votes,opp2_votes。

如果其中一个opps的票数高于另一个,那么我们认为他赢了。如何从这张桌子获得最多的胜利?

5 个答案:

答案 0 :(得分:4)

此查询将查找每个用户的获胜次数,并按降序排序(因此获胜次数最多的是第一行):

SELECT winner, COUNT(*)
FROM
    (
    SELECT opp1 AS winner FROM table
    WHERE opp1_votes > opp2_votes
    UNION ALL
    SELECT opp2 AS winner FROM table
    WHERE opp2_votes > opp1_votes
    )
GROUP BY winner
ORDER BY COUNT(*) DESC

查询说明:

  1. 首先,我们找到了opp1获胜的所有行。我们生成一个表格,其中opp1获胜者列在字段名称“获胜者”下。
  2. 我们和(1)中的做法相同,但现在对于opp2获胜的情况。
  3. 我们联合两张桌子并获得所有比赛中所有获胜者的名单。
  4. 现在,我们按照获胜者ID对结果表进行分组,然后从此分组中选择计数,从而得到获胜者列表,并为每个获胜者列出他/她赢得的次数。
  5. 最后一步是按胜利次数排序,下降。
  6. 注意:

    • 根据上面的查询,如果有平局 - 没有胜利者。如果你想将关系视为其中一个用户的胜利,你需要定义一个打破平局的启发式方法。
    • 如果你真的只想要一个结果,你可以从SELECT TOP 1 winner, ...开始或以LIMIT 1结束,但据我所知,它不会节省一般情况下的计算时间,所以我'留下它。

答案 1 :(得分:0)

SELECT opp, sum(win) wins FROM ( 
    SELECT opp1 opp, CASE WHEN opp1_votes > opp2_votes THEN 1 ELSE 0 END win
      FROM otable
    UNION ALL
    SELECT opp2 opp, CASE WHEN opp2_votes > opp1_votes THEN 1 ELSE 0 END win
      FROM otable
) A
GROUP BY opp
ORDER BY sum(win) DESC LIMIT 1

答案 2 :(得分:0)

SELECT
    CASE WHEN opp1_votes > opp2_votes THEN opp1 ELSE opp2 END as winner,
    COUNT(*)
FROM table
GROUP BY CASE WHEN opp1_votes > opp2_votes THEN opp1 ELSE opp2 END
ORDER BY COUNT(*) DESC

答案 3 :(得分:0)

这个小小的查询将为您赢得所有获胜者以及他以降序获胜的次数:

SELECT
(CASE WHEN `opp1_votes`>`opp2_votes` THEN `opp1` ELSE `opp2` END) `winner`,
COUNT(*) AS `no_of_times`
FROM `matches`
GROUP BY `winner`
ORDER BY `no_of_times` DESC

我们在这里做的是:

  1. 比较在CASE WHEN子句中找出​​哪一个来自opp1_votes和opp2_votes更大
  2. 如果opp1_votes更高,那么我们输出winner列中的opp1,反之亦然
  3. 然后我们按胜利者分组结果
  4. 现在,如果计算每个获胜者所拥有的行数,我们将获得每位获胜者的数字
  5. 结果按no_of_times won
  6. 排序

    如果你只想要获胜次数最多的人,可以在查询结尾添加LIMIT 1,或者你可以包装上面的查询并从中选择max(no_of_times),如下所示:

    SELECT `winner`, MAX(`no_of_times`) AS `no_of_times` FROM (
    SELECT
    (CASE WHEN `opp1_votes`>`opp2_votes` THEN `opp1` ELSE `opp2` END) `winner`,
    COUNT(*) AS `no_of_times`
    FROM `matches`
    GROUP BY `winner`
    ORDER BY `no_of_times` DESC
    ) AS `winners`
    

答案 4 :(得分:-2)

这是否符合您的要求?

select top 1 opp1, 
   (select count(*) 
      from table i 
      where i.opp1 = o.opp1 and i.opp1votes > i.opp2votes) as wins 
from table o 
order desc by wins