查找具有最大出现次数的最大ID

时间:2013-05-27 09:29:17

标签: mysql sql

进行一些练习我不知道如何进行此查询

有这2个表

StudentTable(的 IDstudent 下,....)

考试(的 IDexam ,...,学生,......,结果)

其中

  • 考试中的学生在学生中引用了IDstudent
  • resutl具有布尔值

例如

 StudentTable
 IDstudent
 S0001
 S0002
 S0003


 EXAM
 IDexam     student    result
  1          S0001      true
  2          S0002      true
  3          S0002      true
  4          S0003      false

查询必须显示考试中真实数最多的学生的ID和数字

以示例为例          S0002 2

我试过

  SELECT 
      student, count(1)
  FROM
       Exam  E join StudentTable  S on E.student=S.id_student
  WHERE result='true'
  GROUP by student 

我拥有的是

    S0001    1
    S0002    2

但我不知道如何采取最大值

  • 我该怎么办?

这是架构http://sqlfiddle.com/#!2/895ea/8

的链接

3 个答案:

答案 0 :(得分:4)

试试这个:

  SELECT 
    student, count(1)
  FROM
       Exam  E join StudentTable  S on E.student=S.id_student
  WHERE result='true'
  GROUP by student 
  ORDER by 2 DESC
  LIMIT 0,1
MySQL中的

LIMIT(N,N)子句相当于T-SQL中的 TOP(N)

答案 1 :(得分:3)

我喜欢这个查询的一件事是它支持具有最高true个答案的重复学生。

SELECT  a.*
FROM    StudentTable a
        INNER JOIN
        (
            SELECT  Student
            FROM    Exam
            WHERE   result = 'true'
            GROUP   BY Student
            HAVING  COUNT(*) =
                    (
                        SELECT  COUNT(*) count
                        FROM    Exam
                        WHERE   result = 'true'
                        GROUP   BY Student
                        ORDER   BY count DESC
                        LIMIT   1
                    )
        ) b ON a.IDStudent = b.Student

答案 2 :(得分:2)

试试这个:

SELECT 
  student, count(result) AS number
FROM
   Exam  E join StudentTable  S on E.student=S.id_student
WHERE 
   result='true'
GROUP BY 
   student 
HAVING 
   number = (SELECT COUNT(result) FROM exam WHERE result='true' GROUP BY student ORDER BY 1 DESC LIMIT 1)

链接到SQL Fiddle