2012-04-04 45 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