That title is probably terrible so let me try to explain with an example
I have a table that consists of top 10 teams called _top 10. In order to select all the teams that have played a top 10 team at home I can run this query.
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
This will return a list of all the teams that have played top 10 teams at home along with a number of home many wins against top 10 teams at home they have. What I want included in this list is all the teams that haven't played a top 10 team at home and obviously a zero for wins against top 10 teams at home. Hope this makes sense.
Here is the union code I tried in order to combine the results
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;
UPDATE
I've put everything together and I'm getting
Error Code: 1248. Every derived table must have its own alias
Here is my final query
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;
Any help would be greatly appreciated