2015-09-08 249 views
0

我花了這麼多時間搜索今天,但我甚至不知道要使用哪些關鍵字。所以...合併2 SQL查詢/表

該項目是一個博彩遊戲(足球)的評價。我有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

可能有人需要把'@變量'(即'set @rownum:= 1')連接在一起。所以也許搜索mysql rownum – Drew

+0

所以第二個查詢獲取表中最後一個比賽日的數據。有些玩家可能有那天的數據,有些則沒有。是?什麼是matchdays表的天然獨特鑰匙?每個用戶和比賽日是否有一個條目?或者每個用戶和每天都有更多的條目? –

回答

0

你可以使用條件聚合,即總結的要點,只有當這一天是最後一天:

SELECT 
    p.username, 
    SUM(case when m.matchday = (select max(matchday) from matchdays) then m.points end) 
    AS last_day_points, 
    SUM(m.points) AS total_points 
FROM players p 
INNER JOIN matchdays m ON p.userid = m.userid AND m.season_id = 5 
GROUP BY p.userid 
ORDER BY total_points DESC; 

或用代替連接一個非相關子查詢(MySQL的應該得出相同的執行計劃):

SELECT 
    p.username, 
    SUM(case when m.matchday = last_day.matchday then m.points end) AS last_day_points, 
    SUM(m.points) AS total_points 
FROM players p 
INNER JOIN matchdays m ON p.userid = m.userid AND m.season_id = 5 
CROSS JOIN 
(
    select max(matchday) as matchday 
    from matchdays 
) last_day 
GROUP BY p.userid 
ORDER BY total_points DESC; 
+0

非常感謝!像魅力一樣工作! – Rouven

1

同時使用的查詢與加盟....使用內部聯接如果每個用戶ID在第二個查詢值also.also在第二查詢添加用戶標識也加入

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