子选择列无效问题

时间:2010-02-22 12:49:04

标签: sql mysql select subquery

我有一个sql问题,我在猜测它的子选择中的列名称,因为它尚未分配该名称,但我无法弄清楚如何重新排列它。

select Distinct Captains.Name, Captains.Team, (select count(Winners.Name) from (select HomeTeamCaptain As Name from fixture where fixture.HomeTeamCaptain = Captains.Name And fixture.matchResult = fixture.HomeTeam UNION ALL select AwayTeamCaptain As Name from fixture where fixture.AwayTeamCaptain = Captains.Name And fixture.matchResult = fixture.AwayTeam) As Winners) As Winners From (select fixture.HomeTeamCaptain As Name, HomeTeam As Team From fixture UNION ALL select fixture.AwayTeamCaptain As Name, AwayTeam As Team From fixture) As Captains order by Name;

“Captains.Name”是我需要它来运行Count - Subselect的问题,但却无法掌握它的价值!

1 个答案:

答案 0 :(得分:2)

这对我有用:

select distinct Captains.Name, Captains.Team, 
    (select count(*)  
     from fixture 
     where 
        --I changed this a bit
        (fixture.HomeTeamCaptain = Captains.Name And
         fixture.matchResult = fixture.HomeTeam) 
     OR
        (fixture.AwayTeamCaptain = Captains.Name And 
         fixture.matchResult = fixture.AwayTeam)
    ) As Winners

FROM (select fixture.HomeTeamCaptain As Name, HomeTeam As Team 
     from fixture 
     UNION ALL 
     select fixture.AwayTeamCaptain As Name, AwayTeam As Team 
     from fixture) AS Captains
order by Captains.Name;

你应该考虑创建一个Captains表,并用Id来引用“Home”和“Away”队长。