0

我正在尝试内部加入 2 个临时表
我知道这可以做到,我以前做过,但我完全忘记了如何做

请告诉我
下面是我尝试执行的查询

select tmp1.*, tmp2.cnt from
(
    select 
        1 as ClassificationType,
        tblMatches.IdGame,
        tblMatches.IdPlayer,
        sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore,
        count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount
    from 
        tblMatches  
    group by IdPlayer, IdGame   
) as tmp1
inner join (select IdWinner, count(IdWinner) as cnt from tblCompetitions where IdWinner = tmp1.IdPlayer) as tmp2 
            on tmp2.IdWinner = tmp1.IdPlayer

这将失败,
我认为我不允许在创建 tmp2 的子查询中使用 tmp1

消息 4104,级别 16,状态 1,第 17 行 无法绑定多部分标识符“tmp1.IdPlayer”。

4

4 回答 4

3

您不是要连接两个临时表,而是要连接两个派生表。

除非它位于 SELECT 子句中,否则您无法访问其外部的一个派生表的内部数据。

尝试以下操作:

select tmp1.*, tmp2.cnt from
(
    select 
        1 as ClassificationType,
        tblMatches.IdGame,
        tblMatches.IdPlayer,
        sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore,
        count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount
    from 
        tblMatches      
    group by IdPlayer, IdGame   
) as tmp1
inner join (select IdWinner, count(IdWinner) as cnt from tblCompetitions GROUP BY IdWinner) as tmp2 
                on tmp2.IdWinner = tmp1.IdPlayer
于 2009-12-18T16:02:46.887 回答
2
select
    1 as ClassificationType,
    tmp1.IdGame,
    tmp1.IdPlayer,
    sum(tmp1.Score) as Score,
    sum(tmp1.Points) as Points,
    sum(tmp1.OpponentScore) as OpponentScore,
    count(tmp1.ID) as MatchesCount,
    count(distinct tmp1.IdCompetition) as CompetitionsCount,
    count(tmp2.IdWinner) as cnt
from 
    tblMatches tmp1
    inner join
    tblCompetitions tmp2
        on tmp2.IdWinner = tmp1.IdPlayer
group by
    tmp1.IdPlayer,
    tmp1.IdGame
于 2009-12-18T16:14:41.507 回答
1

where 子句tmp2重复连接条件:

inner join (select IdWinner, count(IdWinner) as cnt 
            from tblCompetitions 
            where IdWinner = tmp1.IdPlayer) as tmp2 
on         tmp2.IdWinner = tmp1.IdPlayer

只需删除该where子句。此外,就像 Astander 在他现在已删除的帖子中指出的那样,第二个查询group by也需要:

inner join (select IdWinner, count(IdWinner) as cnt 
            from tblCompetitions
            group by IdWinner) as tmp2 
on         tmp2.IdWinner = tmp1.IdPlayer

您不能从子查询中引用外部查询的原因是这会使联接的右侧部分依赖于联接的左侧部分。

于 2009-12-18T16:02:49.533 回答
1

您实际上不应该需要第二个子查询。那这个呢?

SELECT tmp1.ClassificationType, tmp1.IdGame, tmp1.IdPlayer,
       COUNT(tblCompletions.IdWinner) as cnt FROM
(
    SELECT 
        1 as ClassificationType,
        tblMatches.IdGame,
        tblMatches.IdPlayer,
        sum(Score) as Score, sum(Points) as Points, sum(OpponentScore) as OpponentScore,
        count(ID) as MatchesCount, count(distinct IdCompetition) as CompetitionsCount
    FROM 
        tblMatches      
    GROUP BY IdPlayer, IdGame   
) as tmp1
INNER JOIN tblCompletions ON tmp1.IdPlayer = tblCompletions.IdWinner
GROUP BY tmp1.ClassificationType, tmp1.IdGame, tmp1.IdPlayer
于 2009-12-18T16:06:23.307 回答