2017-02-26 331 views
1

我的表如下所示:與多個結果連接兩個表放在一個表

tbl_teams 
id, teamname, created 

tbl_teamstats 
id, rank, rating, wins, losses, tbl_teams_id, created 

我想根據tbl_teamstats這兩個表合併在一起「創建遞減限制1」 例如查詢

SELECT TS.*, T.* FROM tbl_teamstats as TS 
LEFT JOIN tbl_teams as T 
ON T.id = TS.tbl_teams_id 

會回到這樣的事情

TS.id TS.rank TS.rating TS.wins TS.losses T.id T.teamname    T.created 
14871 2  2522  168  26   2  teamname1    23/02/2017 17:55 
14688 2  2540  168  25   2  teamname1    23/02/2017 17:55 
2683 2  2535  167  25   2  teamname1    23/02/2017 17:55 
2612 2  2529  166  25   2  teamname1    23/02/2017 17:55 
2590 2  2523  165  25   2  teamname1    23/02/2017 17:55 
2448 2  2517  164  25   2  teamname1    23/02/2017 17:55 
2346 2  2511  163  25   2  teamname1    23/02/2017 17:55 
234  2  2505  162  25   2  teamname1    23/02/2017 17:55 
1  1  2570  171  19   1  teamname2    23/02/2017 17:55 

WH在我希望它看起來像:

TS.id TS.rank TS.rating TS.wins TS.losses T.id T.teamname    T.created 
14871 2  2522  168  26   2  teamname1    23/02/2017 17:55 
1  1  2570  171  19   1  teamname1    23/02/2017 17:55 

(只顯示來自tbl_teamstat由TS.id訂購一個結果)

可能有人請幫助我,或點我在正確的方向?將不勝感激!

回答

1

您可以在子查詢中找到來自tbl_teamstats的每個tbl_team_id的最大ID並將其與tbl_teamstats結合使用。然後,根據需要進行連接。

select * 
from (
    select t1.* 
    from tbl_teamstats t1 
    join (
     select tbl_teams_id, 
      max(id) id 
     from tbl_teamstats 
     group by tbl_teams_id 
     ) t2 on t1.tbl_teams_id = t2.tbl_teams_id 
     and t1.id = t2.id 
    ) ts 
left join tbl_teams as T on T.id = TS.tbl_teams_id 
+0

謝謝添加GROUP BY條款!這解決了它:) –

0

SELECT TS.*, T.* FROM tbl_teamstats as TS 
LEFT JOIN tbl_teams as T 
ON T.id = TS.tbl_teams_id 
GROUP BY TS.rank