合并2个SQL查询/表

时间:2015-09-08 12:47:50

标签: mysql

我今天花了很多时间在Google上搜索,但我甚至不知道要使用哪些关键字。所以...

该项目是对博彩游戏(足球)的评估。我有2个SQL查询:

SELECT players.username, players.userid, matchdays.userid, matchdays.points, SUM(points) AS gesamt
FROM players INNER JOIN matchdays ON players.userid = matchdays.userid AND matchdays.season_id=5
            GROUP BY players.username
            ORDER BY gesamt DESC

我的第二个问题是:

SELECT max(matchday) as lastmd, points, players.username from players INNER JOIN matchdays ON players.userid = matchdays.userid WHERE matchdays.season_id=5 AND matchday=
 (select max(matchday) from matchdays)group by players.username ORDER BY points DESC

第一个将每个比赛日的积分相加并显示总和。 第二个显示了上一个比赛日的积分。

我的目标是合并这两个查询/表,以便输出像

这样的表

排名|用户名|积分上一个比赛日|总分|

我甚至不知道从哪里开始或寻找什么。任何帮助将不胜感激;)

2 个答案:

答案 0 :(得分:1)

同时使用join和join ....如果每个userid在第二个查询中都有值,则使用内部联接。也可以在第二个查询中添加userid以进行连接

    SET @rank = 0;

    SELECT  @rank := rank + 1,
                t1.username,
                t2.points,
                t1.gesamt
    FROM        (
                    SELECT  players.username, players.userid puserid, matchdays.userid muserid, matchdays.points, SUM(points) AS gesamt
                    FROM        players INNER JOIN matchdays ON players.userid = matchdays.userid AND matchdays.season_id=5
                 GROUP BY players.username           
              )t1
              INNER JOIN 
              ( 
                SELECT players.userid, max(matchday) as lastmd, points, players.username 
                    from players INNER JOIN matchdays ON players.userid = matchdays.userid 
                    WHERE matchdays.season_id=5 AND matchday=
                    (select max(matchday) from matchdays)group by players.username
                )t2
                ON t1.puserid = t2.userid
    ORDER BY t1.gesamt 

答案 1 :(得分:0)

您可以使用条件聚合,即仅在当天是最后一天时对点数求和:

tr

或者使用连接而不是非相关子查询(MySQL 应该来到同一个执行计划):

.fixed{
    display: table;
    left: 0;
    position: fixed;
    top: 0;
    width: 824px;
}