我遇到了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 :(得分: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 :(得分:1)
不漂亮,但它有效。我先将选票分组,然后获得排名。
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