2012-04-04 52 views
0

我有一个student_table表,其中有两列student_name(具有uniqe约束)student_marks。从这张表格中,我需要得到具有第三高分的学生的记录。查询获得第三高分

我想这一点,但它是不正确的:

select * from student_table orderby(marks) enum(marks)=3; 

如何解决这个查询?

+0

是student_name唯一吗? 1名学生有多个分数? – 2012-04-04 11:27:10

+0

如果允许,你想如何处理关系?例如,两名学生有100分,三分有98分,五分有95分? – pilcrow 2012-04-04 16:57:03

回答

1
select * from students_table orderby marks limit 2,1 

检查此网址到更多关于限制http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

+1

select * from student_table order by(marks)limit 2,3; – user1308308 2012-04-04 11:43:42

+0

谢谢,你能解释答案吗? – user1308308 2012-04-04 11:47:20

+0

你能通过我在我的回答给出的网址 – 2012-04-04 11:48:47

1

在MySQL中,你可以这样做:

SELECT * FROM Student_Table ORDER BY Marks LIMIT 2, 1 
+0

感谢您的回答,它给3条记录不是第三条记录?我只需要得到第三条记录。 – user1308308 2012-04-04 11:29:02

+0

我可以有任何其他的解决方案与使用限制.. – user1308308 2012-04-04 11:45:25

+0

它导致空记录... – user1308308 2012-04-04 11:46:45

3

如果你只是想第三记录:

SELECT * FROM student_table ORDER BY marks DESC LIMIT 2,1 

有一个读关于LIMIT命令。

5

这里是一个非常简单的解决方案

select * 
from marks 
order by marks desc 
limit 2,1 

与限制,你可以使用偏移量和长度。这里偏移量设置为2,因为它从0开始。对于第三条记录。 1是限制。

这里是另一种解决方案

$res=mysql_query("SELECT * from marks order by marks desc"); 
mysql_data_seek($res, 2); 
$row=mysql_fetch_assoc($res)); 
4

试试这个

SELECT * FROM `student_table` ORDER BY marks DESC LIMIT 2,1 
0

下面的查询将返回所有记录的学生在第三位,无论有多少学生并列第一,第二或第三名。

SELECT student_table.name, student_table.marks 
    FROM student_table 
WHERE student_table.primary_key IN ( SELECT ranked.primary_key 
              FROM student_table ranked 
            LEFT JOIN student_table others 
               ON ranked.marks < others.marks 
             GROUP BY 1 
             HAVING COUNT(DISTINCT others.marks) + 1 = 3) 

例如,如果student_table看起来是这样的:

+---------+-------+ 
| name | marks | 
+---------+-------+ 
| Alpha | 100 | 
| Able | 100 | 
| Bravo | 98 | 
| Baker | 98 | 
| Bone | 98 | 
| Charlie | 93 | <-- 3rd place by marks 
| Chimp | 93 | <-- 3rd place by marks 
| Delta | 85 | 
| Echo | 80 | 
| Ebert | 80 | 
+---------+-------+ 

查询将产生:

+---------+-------+ 
| name | marks | 
+---------+-------+ 
| Charlie | 93 | 
| Chimp | 93 | 
+---------+-------+ 

顺便说一句,查询将变得更容易一些,如果MySQL的支持DENSE_RANK (),但您可以使用上面的子查询来模拟该函数。

0

使用以下查询
QUERY:从student_table选择*,其中在标记(选择student_table组标记用标记顺序用标记DESC LIMIT 2,1);

+0

学习[如何使用代码块](http://stackoverflow.com/editing-help) – 2018-02-03 08:43:17