2015-10-17 96 views
1

我試圖從MySQL服務器中的數據中提取排​​行榜。這是爲了顯示某些玩家在每張地圖上的圈速。Mysql左外部聯接篩選器

我,我想出了到目前爲止當前的查詢是這樣的:

select d1.* 
from surf_times d1 
left outer join surf_times d2 
on (d1.Name = d2.Name and d1.Time > d2.Time) 
where d2.Name is null 
order by Time; 

這將返回正確的結果,但是我需要通過地圖進行過濾。一個例子表可在http://sqlfiddle.com/#!2/3e9c6/1

該查詢發現將響應:

SteamID    Name     Map    Time Date 
76561197991519598 Kuratheris    surf_utop  60.05 1445107360 
76561198129490626 xXNightw0lfXx   surf_ace  60.84 1445106920 
76561198156238243 ☆ The Pic ☆   surf_utop  62.35 1445107724 
76561198049179442 J4N412N3    surf_utop  69.53 1445107519 
76561197994977992 Rockape2620    surf_ace  72.26 1445107047 

這幾乎是正確的,但我的查詢需要只返回選定的,而不是從所有地圖次地圖。正確的查詢應與例如「surf_utop」所選擇的地圖上15倍應對應如下表響應:

SteamID    Name     Map    Time Date 
76561197991519598 Kuratheris    surf_utop  60.05 1445107360 
76561198156238243 ☆ The Pic ☆   surf_utop  62.35 1445107724 
76561198049179442 J4N412N3    surf_utop  69.53 1445107519 

我看了一下,如SQL Select only rows with Max Value on a Column但一直沒能等問題弄明白。

回答

1

你不需要JOIN再次對整個表,你可以使用:

SELECT st.* 
FROM surf_times st 
WHERE st.Time = 
    (SELECT MIN(t.Time) 
    FROM surf_times t 
    WHERE t.SteamID = st.SteamID AND t.Map = st.Map) 
     AND st.Map = 'surf_utop' -- or any other map 
GROUP BY st.SteamID 
ORDER BY st.Time 
LIMIT 15; 
+0

這是不好的建議。從屬子查詢比再次加入表格要糟得多。你應該看看這是什麼 –

+0

這似乎不太可能,但也許我誤解了這個問題 – Strawberry

+0

JOIN是相當昂貴的內存。它基本上加載整個表,並在使用WHERE子句 –

1

所以只需在您的WHERE選擇的地圖上添加即可。

select d1.* 
from surf_times d1 
left outer join surf_times d2 
on (d1.Name = d2.Name and d1.Time > d2.Time) 
where d2.Name is null AND d1.map = 'surf_utop' 
order by Time 
limit 15; 

fiddle example

結果:

+-------------------+-----------------+-----------+-------+------------+ 
|  SteamID  |  Name  | Map | Time | Date | 
+-------------------+-----------------+-----------+-------+------------+ 
| 76561197991519598 | Kuratheris  | surf_utop | 60.05 | 1445107360 | 
| 76561198156238243 | ☆ The Pic ☆ | surf_utop | 62.35 | 1445107724 | 
| 76561198049179442 | J4N412N3  | surf_utop | 69.53 | 1445107519 | 
+-------------------+-----------------+-----------+-------+------------+