2011-03-04 26 views
1

目前,我有以下模式如何執行以下多個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

第一次加入之後,進行第二次加入。然後你的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 
+0

我仍然得到雙重結果 – deltanovember