【问题标题】:Join multiple tables and order by sum of row连接多个表并按行总和排序
【发布时间】:2015-02-28 18:51:56
【问题描述】:

最近开始研究一个匹配系统,在这个系统中有 2 个表。一桌比赛,一桌排位。

排名表是这样开始的

table_ranks:

date
playeruid
rank

table_matches:

date
playeruid
playerpoints

我现在正试图按玩家的分数来排序。但是,为了做到这一点,我做了一个查询:

SELECT * FROM table_ranks ORDER by rank DESC

但现在我意识到,我需要在排名顶部添加玩家点数。所以基本上,我需要将玩家积分添加到玩家当前的排名中。所以,如果我有这个作为示例行:

table_ranks:

2/20/15
Player1
56

table_matches:

2/27/15
Player1
5

我需要构建一个查询,获取 player1 的 56,在比赛中查找 player1 以及它看到的任何地方,它需要添加他的 5 分,使其总和为 56。一旦确定,它将ORDER 通过这个值来确定谁与什么排名。如何开始查询?我知道为了加入表格,我需要这样开始:

"SELECT table_ranks., table_matches. from table_ranks, table_matches ORDER by RANK..."

然后要完成它,我必须获取排名的当前值,然后获取它所指的特定玩家并获取所有比赛并将所有玩家积分加到他的排名中,然后确定如何排序.

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    试试这个:

    SELECT r.playeruid, r.date AS rank_date, m.date AS macthes_date, 
           (r.rank + m.playerpoints) AS total_points  
    FROM table_ranks r INNER JOIN table_matches m ON r.playeruid = m.playeruid  
    ORDER BY total_points DESC
    

    此查询假定 playeruid 在两个表中都是唯一的。

    【讨论】:

      【解决方案2】:

      尝试以下查询。我在一个相似的结构上进行了测试,它应该可以工作

       SELECT * , playeruid AS player_id, (
          SELECT SUM( playerpoints ) 
          FROM  `table_matches` 
          WHERE playeruid = player_id
       ) AS points
       FROM table_ranks 
       ORDER BY points DESC
      

      【讨论】:

        猜你喜欢
        • 2015-07-29
        • 1970-01-01
        • 2022-10-01
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-19
        相关资源
        最近更新 更多