2014-11-24 272 views
0

問題:如何使MySQL查詢子查詢中結合2個結果1個結果

如何使這個查詢結果合併爲1分的結果?

select *, count(winner) as count 
    from (select case radiant_win 
       when 1 then radiant_name 
       else dire_name 
      end as winner, 
      radiant_team_id, 
      dire_team_id, 
      series_id, 
      series_type 
     from matches 
     where leagueid = 2096 and 
       start_time >= 1415938900 and 
      ((radiant_team_id= 1848158 and dire_team_id= 15) 
       or (radiant_team_id= 15 and dire_team_id= 1848158)) 
     ) as temp 
    group by winner; 

當前結果

下面是當前查詢結果

Results from the query

預期的效果

下面是我想要的結果

Desired results

回答

1

似乎要彙總所有的比賽兩隊之間並指望有多少次,每次他們是勝利者,如果是這樣:

要簡化事情,創建一個視圖:

create view v_matches as 
select radiant_team_id as team1_id, radiant_win as team1_win, dire_team_id as team2_id, 1 - radiant_win as team2_win, leagueid, start_time, series_id, series_type 
from matches 
union 
select dire_team_id as team1_id, 1 - radiant_win as team1_win, radiant_team_id as team2_id, radiant_win as team2_win, leagueid, start_time, series_id, series_type 
from matches 

然後:

select team1_id, sum(team1_win) as team1_wins, team2_id, sum(team2_win) as team2_wins, series_id, series_type 
from v_matches 
where leagueid = 2096 and start_time >= 1415938900 
    and team1_id = 1848158 and team2_id = 15 

您可以將團隊名稱添加到視圖中或使用teams表格加入第二個查詢。