SQL phpMyAdmin:列出比主场胜利更多客场胜利的球队

时间:2016-10-23 11:53:32

标签: mysql

我有一个名为Football的数据库,其中包含以下表格:足球运动员,球队,经理,比赛。我试图列出比主场胜利更多客场胜利的球队。主场胜利是一支球队在主场比赛中的主场比赛,主场进球数超过了客场进球的数量 - 与客场胜利的情况相反。

我可以使用以下方式显示主场获胜次数:

SELECT T.TeamName, COUNT(*) AS HomeWins
FROM Teams T, Matches M
WHERE M.HomeTeamID = T.TeamID AND M.HomeGoals > M.AwayGoals

同样获得客场胜利的数量。

当我试图将两者结合在一起让球队获得更多胜利而不是主场胜利时我得到了一个错误,我尝试了几种不同的方式,包括:

SELECT T.TeamName
FROM Teams T, Matches M
WHERE M.HomeTeamID = T.TeamID
HAVING COUNT (M.HomeGoals > M.AwayGoals) > COUNT(M.AwayGoals > M.HomeGoals)

SELECT T.TeamName
FROM Teams T, Matches M
WHERE M.HomeTeamID = T.TeamID AND (COUNT (M.HomeGoals > M.AwayGoals) > COUNT(M.AwayGoals > M.HomeGoals)

SELECT T.TeamName
WHERE
  (COUNT DISTINCT(TeamID) FROM Teams T, Matches M WHERE M.HomeTeamID = T.TeamID AND M.HomeGoals > M.AwayGoals) >
  (COUNT DISTINCT(TeamID) FROM Teams T, Matches M WHERE M.AwayTeamID = T.TeamID AND M.HomeGoals < M.AwayGoals)

这些都不起作用。我知道我可能会遗漏一些非常基本的东西,但我真的很感激一些见解,因为我似乎无法让它发挥作用。

2 个答案:

答案 0 :(得分:0)

我已经为您的示例创建了一个示例数据库,并设法编写一个返回您要求的查询。它有点复杂,所以我先显示查询然后将其分解:

SELECT away_query.id, away_query.name, away_query.away_wins, home_query.home_wins
FROM (
    SELECT teams.id, teams.name, count(*) as away_wins
    FROM teams
    JOIN matches ON teams.id = matches.away_team_id AND matches.away_goals>matches.home_goals
    GROUP BY teams.id
) as away_query
JOIN (
    SELECT teams.id, teams.name, count(*) as home_wins
    FROM teams
    JOIN matches ON teams.id = matches.home_team_id AND matches.home_goals>matches.away_goals
    GROUP BY teams.id
) as home_query
ON away_query.id=home_query.id
HAVING away_query.away_wins>home_query.home_wins

我注意到的第一件事是你的SQL中缺少的是JOIN子句,这在组合来自多个表的数据时是必不可少的。 我写的第一个查询是检索每个团队的胜利数量的那个:

SELECT teams.id, teams.name, count(*) as away_wins
FROM teams
JOIN matches ON teams.id = matches.away_team_id AND matches.away_goals>matches.home_goals
GROUP BY teams.id

JOIN用于组合团队并匹配&#34;团队&#34;的ID字段上的表格。 table和match_team_id匹配表的字段,filter只匹配客队赢得的地方。 GROUP BY让它计算每队的客场胜利。

我对主场胜利做了同样的询问:

SELECT teams.id, teams.name, count(*) as home_wins
FROM teams
JOIN matches ON teams.id = matches.home_team_id AND matches.home_goals>matches.away_goals
GROUP BY teams.id

现在我已经查询了每支球队的客场胜利,以及主场胜利,我只需要将它们结合起来并过滤掉比主场胜利更多的胜利&#34;。 我是用子查询做的。 FROM是离胜查询,由主胜查询加入。 ON在id字段上组合了2个查询,现在剩下的就是用HAVING子句过滤它:

HAVING away_query.away_wins>home_query.home_wins

结果是这个答案中的第一个(非常长的)查询。

答案 1 :(得分:0)

对于任何有兴趣的人,我设法让这个工作起来但我必须为客场胜利和主场胜利创建两个观点并使用这些观点来查询:

CREATE VIEW HomeWins (TeamName, HomeWins) 
AS SELECT T.TeamName, COUNT(*) 
FROM Teams T, Matches M 
WHERE M.HomeTeamID = T.TeamID 
AND M.HomeGoals > M.AwayGoals

CREATE VIEW AwayWins (TeamName, AwayWins) 
AS SELECT T.TeamName, COUNT(*) 
FROM Teams T, Matches M 
WHERE M.HomeTeamID = T.TeamID 
AND M.HomeGoals < M.AwayGoals

SELECT A.TeamName 
FROM HomeWins H, Awaywins A 
WHERE H.HomeWins < A.AwayWins 
AND A.TeamName = H.TeamName