如何进行以下多个SQL连接?

时间:2011-03-04 06:42:21

标签: sql

目前我有以下架构

DAILY

match_id,user_id,round,score,result, tournament_id

目前我有一个查询以赢得百分比的顺序生成玩家,以及得分和点数等。

user_id     username    winpercent  totalgames  pointsfor   pointsagainst
3569    User1   100.00000   20  9193    6960
11786   User2   100.00000   11  4549    3859
11932   User3   100.00000   5   1259    1120

查询如下

SELECT PointsFor.user_id,username,
sum(case when PointsFor.result='Won' then 1 Else 0 End)/sum(case when PointsFor.result<>'' Then 1 Else 0 End)*100.0 As winpercent,
sum(case when PointsFor.result<>'' Then 1 Else 0 End) as totalgames,
sum(PointsFor.score) as pointsfor,
sum(PointsAgainst.score) as pointsagainst
FROM users,`daily` PointsFor
JOIN `daily` PointsAgainst
  on PointsFor.match_id = PointsAgainst.match_id
  and PointsFor.user_id <> PointsAgainst.user_id
where PointsFor.user_id=users.id and
    PointsFor.tournament_id=24        
group by user_id
order By WinPercent desc, totalgames desc

我想根据回合和结果添加一个进一步的限制。基本上我想限制特定范围的轮次和特定范围的结果。我试过添加以下内容

JOIN (select user_id from daily where round > 25 and (result='Won' or result='Lost')) recent on PointsFor.user_id = recent.user_id

就在我的where子句之上,但我最终获得了两倍的结果,即Totalgames是20,当它应该只有10等等。这个连接的正确方法是什么?

1 个答案:

答案 0 :(得分:-1)

在第一次加入之后,放入第二次加入。然后你的where子句。

SELECT PointsFor.user_id,username,
sum(case when PointsFor.result='Won' then 1 Else 0 End)/sum(case when PointsFor.result<>'' Then 1 Else 0 End)*100.0 As winpercent,
sum(case when PointsFor.result<>'' Then 1 Else 0 End) as totalgames,
sum(PointsFor.score) as pointsfor,
sum(PointsAgainst.score) as pointsagainst
FROM users,`daily` PointsFor
JOIN `daily` PointsAgainst
  on PointsFor.match_id = PointsAgainst.match_id

然后

JOIN (select user_id from daily where round > 25 and (result='Won' or result='Lost')) recent on PointsFor.user_id = recent.user_id\

然后

where PointsFor.user_id <> PointsAgainst.user_id
and  PointsFor.user_id=users.id and
    PointsFor.tournament_id=24        
group by user_id
order By WinPercent desc, totalgames desc