查询1表两次,获得2个不同的计数结果

时间:2016-03-10 16:53:08

标签: mysql

我对复杂的mysql语句的想法非常感兴趣,但我正在努力处理文档。

我有一个足球比赛表基本上是这样的:

match_id | home_team_id | away_team_id | home_score | away_score
----------------------------------------------------------------
    1    | 2            | 3            | 1          | 0        
    2    | 5            | 2            | 0          | 2

我需要做一些查询才能做我想要的事情

  1. 为球队效力的总比赛
  2. 团队中的总胜利
  3. 团队总胜利
  4. 我会通过几个艰难的查询来做这件事,然后再处理它们:

    SELECT 
        COUNT(match_id), SUM(home_score)
    FROM 
        matches 
    WHERE 
        home_team_id=2 
    AND 
        home_score > away_score
    

    SELECT 
        COUNT(match_id), SUM(away_score) 
    FROM 
        matches 
    WHERE 
        away_team_id=2 
    AND 
        away_score > home_score
    

    这似乎是很多小的重复。我以为我可以做这样的工会:

    SELECT 
        COUNT(match_id) as home_wins
    FROM 
        matches
    WHERE 
        home_team_id=2
    AND 
        home_score > away_score
    UNION ALL
    SELECT 
        COUNT(match_id) as away_wins
    FROM 
        matches
    WHERE 
        away_team_id=2
    AND 
        away_score > home_score
    

    哪种方法有效,但我认为它正在合并结果。如何使用一个查询完成?

0 个答案:

没有答案