获得仅仅显示胜利者的比赛的输家

时间:2014-08-16 19:15:42

标签: mysql

我有一个名为teams(id,name),match(id,team1,team2),results(match,winner)的表

如何根据表格匹配和结果选择匹配x的输家?可以用MySQL做,还是必须在PHP上做?

编辑: 匹配 - team1和team2参考团队(id) 结果 - 匹配引用匹配(id)和获胜者引用团队(id)

我需要得到失败球队的身份。

2 个答案:

答案 0 :(得分:2)

假设你不允许抽签,输家是参加比赛并且不是赢家的球队,所以(使用X作为比赛ID):

SELECT name
FROM   teams
WHERE  id IN (SELECT team 
              FROM   (SELECT match, team1 AS team
                      FROM   matches
                      WHERE  id = X
                      UNION ALL
                      SELECT match, team1 AS team
                      FROM   matches
                      WHERE  id = X) t
              JOIN   results
              ON     t.match = winner.match AND t.team != results.winner)

答案 1 :(得分:2)

我会使用joincase语句执行此操作:

select m.id,
       (case when r.winner = m.team1 then team2
             else team1
        end) as loser
from matches m join
     results r
     on m.id = r.match;

因为您只想要id,所以不需要teams表。