2014-06-26 80 views
-1

我有一個來自mySQL的問題,實際上我想顯示學生的最高票數在學科全名。 這裏的代碼MySQL - 顯示最高的投票

$query="SELECT student_tbl.fullname, student_tbl.subject, 
     COUNT(student_tbl.fullname)AS rating 
     FROM student_tbl 
     INNER JOIN subject_tbl 
     ON student_tbl.subject= subject_tbl.subjname 
     GROUP BY subject ORDER BY num, 
     COUNT(fullname) DESC"; 


student_tbl     subject_tbl 
    | fullname | subject|  | subjname | num | 
    ====================  ================ 
    | John  | Math |  | Math  | 1 | 
    | Rey  | Math |  | Science | 2 | 
    | Wey  | Science |  | English | 3 | 
    | Xin  | Science |  ================= 
    | Nick  | English | 
    | Mi  | English | 
    | John  | Math | 
    | Xin  | Science | 
    | Mi  | English | 
    ====================== 

下面是輸出到我的代碼:

| fullname | Subject | Votes | 
============================ 
| John  | Math  | 2 | 
| Wey  | Science | 2 | 
| Nick  | English | 2 | 

,這是我想要的輸出:

| fullname | Subject | Votes | 
============================ 
| John  | Math  | 2 | 
| Xin  | Science | 2 | 
| Mi  | English | 2 | 
+0

看到,因爲你的受試者(大概)一個'num'的PK表,你爲什麼那麼存儲'subjname'旁邊的學生'fullname'?另外,你在第一個表上缺少一個重要的主鍵。 – Strawberry

回答

1
SELECT s1.fullname, s1.subject, COUNT(s1.fullname) AS rating 
FROM student_tbl s1 
INNER JOIN subject_tbl s2 
    ON s1.subject= s2.subjname 
GROUP BY subject, fullname 
    HAVING COUNT(fullname) = (
    SELECT COUNT(fullname) FROM student_tbl 
    WHERE s1.subject = subject 
    GROUP BY fullname 
    ORDER BY COUNT(fullname) DESC 
    LIMIT 1 
) 
ORDER BY num, COUNT(fullname) DESC 

SqlFiddle:http://sqlfiddle.com/#!2/aea20

我強烈建議你使用數字鍵而不是字符串鍵。

1

不漂亮,但它的作品。我先將選票分組,然後獲得排名。

SQL FIDDLE DEMO

SELECT fullname, subject, votes 
FROM (SELECT fullname,subject,votes, 
      (CASE subject WHEN @curtype THEN @currow := @currow + 1 
       ELSE @currow := 1 AND @curtype := subject end) + 1 AS rank 
     FROM (SELECT fullname,subject,Count(1) AS Votes 
         FROM student_tbl 
     GROUP BY fullname,subject) a,(SELECT @currow := 0, @curtype := '') r 
     ORDER BY subject,votes DESC) b 
WHERE rank = 1