使用IN从表中选择对象

时间:2013-03-19 19:53:08

标签: mysql sql

这个标题可能很糟糕,所以让我试着用一个例子来解释

我有一个由名为_top 10的前10名球队组成的桌子。为了选择在国内打过前10名球队的所有球队,我可以运行此查询。

SELECT      g.home_team,
            IFNULL(SUM(g.home_wins), 0) AS formula 
FROM        games g
WHERE 
            away_team IN (SELECT team_id FROM _top_10) 
GROUP BY    g.home_team 
ORDER BY    formula DESC

这将返回所有在主场打出前10名球队的球队的名单,以及他们在主场对阵前10名球队的许多胜利。我想要包括在这个名单中的是所有没有在主场打过前十名球队的球队,显然对于主场前十名球队的胜利是零。希望这是有道理的。

这是我试图结合结果的联合代码

SELECT      g.home_team,
            IFNULL(SUM(g.home_wins), 0) AS formula ,
            t.*
FROM        games g
INNER JOIN _top_10 AS t ON g.away_team = t.team_id

UNION

SELECT      g.home_team,
            SUM(0) AS formula ,
            t.*
FROM        games g
LEFT JOIN _top_10 AS t ON g.away_team = t.team_id
WHERE t.team_id IS NULL
GROUP BY    g.home_team 
ORDER BY    formula DESC;

更新

我把所有东西放在一起,我得到了

  

错误代码:1248。每个派生表必须有自己的别名

这是我的最终查询

SELECT     IF(@last_ranking <> formula, @current_rankings := @current_rankings + 1, @current_rankings)  AS rank, 
            @last_ranking := formula, 
            prequery.team, 
            prequery.formula
FROM        (select @current_rankings := 0) sqlvars, 
            (SELECT    team, 
                        SUM(score) formula 
            FROM (SELECT     g.home_team, 
                            SUM(CASE WHEN t.team_id IS NULL THEN 0 ELSE g.home_wins END) AS formula 
            FROM            games g LEFT JOIN 
                        _top_10 AS t ON g.away_team = t.team_id 
            WHERE       
                        g.season = 2012 AND 
                        g.completed = 1 
        UNION ALL SELECT     g.away_team, 
                        SUM(CASE WHEN t2.team_id IS NULL THEN 0 ELSE g.away_wins END) AS formula 
            FROM        games g LEFT JOIN 
                        _top_10 AS t2 ON g.home_team = t2.team_id 
            WHERE      
                        g.season = 2012 AND 
                        g.completed = 1), 
                            (SELECT @current_rankings := 0, @last_ranking := 0) r 
                GROUP BY team ORDER BY formula DESC ) prequery;

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

JOIN表而不是IN谓词:

SELECT      g.home_team,
            IFNULL(SUM(g.home_wins), 0) AS formula ,
            t.*
FROM        games g
INNER JOIN _top_10 AS t ON g.away_team = t.team_id
GROUP BY    g.home_team 
ORDER BY    formula DESC;

要让那些没有在家中排名前十的球队,请LEFT JOIN使用WHERE t.team_id IS NULL

SELECT      g.home_team,
            IFNULL(SUM(g.home_wins), 0) AS formula ,
            t.*
FROM        games g
LEFT JOIN _top_10 AS t ON g.away_team = t.team_id
WHERE t.team_id IS NULL
GROUP BY    g.home_team 
ORDER BY    formula DESC;

更新

您可以使用一个查询执行此操作:

SELECT 
  g.home_team, 
  SUM(CASE WHEN t.team_id IS NULL THEN 0 ELSE g.home_winsEND) AS formula,
  ...
FROM games g 
LEFT JOIN _top_10 AS t ON g.away_team = t.team_id 
GROUP BY g.home_team, ...;