2011-07-26 36 views
0

分組我有FF表:複雜的排序和使用MySQL

--------------------------- 
ID | ChapterNo | HitCount | 
--------------------------- 
1 | 2  | 1000 | 
2 | 2  | 2000 | 
3 | 1  | 3000 | 
4 | 3  | 1000 | 
5 | 1  | 3500 | 
--------------------------- 

基本上我需要存檔這樣的結果:

獲取所有的獨特chapterno其中每個具有最高的命中計數,然後才能通過chapterno降

ID | ChapterNo | HitCount | 
--------------------------- 
4 | 3  | 1000 | 
2 | 2  | 2000 | 
5 | 1  | 3500 | 
--------------------------- 

我試過ff。查詢:

SELECT t1.*, Max(t1.hitcount) AS maxhit 
FROM chapter as t1 
GROUP BY t1.chapterno 
ORDER BY t1.chapterno DESC 

但有些如何不返回最高hitcount。

我該如何解決這個問題?

謝謝

回答

4
SELECT t1.*, t1.hitcount AS maxhit 
FROM chapter as t1 
WHERE t1.hitcount = (select max(hitcount) from chapter where chapterno = t1.chapterno) 
ORDER BY t1.chapterno DESC 
+0

+1的完美解決方案 – diEcho

+0

這是如此的相似,我以前的查詢之一。但我沒有想到這個子查詢中的哪個部分。謝謝@StevieG – DucDigital

2
SELECT t1.id, t1.chapterno, t2.maxhits 
FROM chapter as t1, 
    (SELECT id, chapterno, Max(hitcount) AS maxhits 
    FROM chapter 
    GROUP BY chapterno) AS t2 
WHERE t2.chapterno = t1.chapterno 
AND t1.hitcount = t2.maxhits 
ORDER BY t1.chapterno DESC 
1

嘗試這一個 -

SELECT c1.id, c1.ChapterNo, c1.HitCount FROM chapter c1 
JOIN (SELECT ChapterNo, MAX(HitCount) max_hitCount 
     FROM chapter 
     GROUP BY ChapterNo) c2 
ON c1.ChapterNo = c2.ChapterNo AND c1.HitCount = c2.max_hitCount 
ORDER BY c1.ChapterNo DESC; 
1
SELECT t1.*, t1.hitcount AS maxhit 
FROM chapter as t1 
WHERE t1.hitcount = (
    SELECT MAX t1.hitcount 
    from chapter as t2 
    where t2.ChapterNo = t1.chapterNo 
) 
ORDER BY t1.chapterno DESC

它使用相關子查詢,它可以成爲效率不高。另一種可能是在from或left join中使用不相關的查詢。

More info on this article

1

雖然所有這些答案,都是完美的,我認爲它也可以用自做JOIN

SELECT * 
FROM chapter ch 
WHERE (
    SELECT COUNT(*) FROM chapter ch2 
    WHERE ch2.chapterno = ch.chapterno and ch2.hitcount > ch.hitcount 
) <= 2;