Mysql Query为表中的所有学生提取第二低分

时间:2014-12-18 10:32:02

标签: mysql mysqli

我有一张如下表格。我想取所有学生的第二个最低分标记(基于标记的升序)。请帮我查询一下。

id  | student_id | subject_id | marks
--------------------------------------
1   |     1      |      1     |   15
2   |     2      |      1     |   12      
3   |     2      |      3     |   19
4   |     2      |      5     |   14
5   |     4      |      1     |   12
6   |     4      |      2     |   14
7   |     4      |      4     |   13
8   |     4      |      5     |   17
9   |     5      |      1     |   18
10  |     5      |      6     |   19
11  |     5      |      7     |   15

所以我想要下面的结果。查询应仅获取上表中所有学生的第二个最低分数科目。学生ID 1只有一个科目。所以我不需要那个。

id  | student_id | subject_id | marks
--------------------------------------
4   |     2      |      5     |   14
7   |     4      |      4     |   13
9   |     5      |      7     |   18

2 个答案:

答案 0 :(得分:2)

您可以使用substring_index() / group_concat()技巧:

执行此操作
select substring_index(substring_index(group_concat(id order by marks asc), ',', 2), ',', -1) as id,
       student_id,
       substring_index(substring_index(group_concat(subject_id order by marks asc), ',', 2), ',', -1) as subject_id,
       substring_index(substring_index(group_concat(marks order by marks asc), ',', 2), ',', -1) as marks  
from marks
group by student_id
having count(*) >= 2;

请注意,这会将列作为字符串而不是原始数据类型返回。

答案 1 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,student_id INT NOT NULL
,subject_id INT NOT NULL
,marks INT NOT NULL
);

INSERT INTO my_table VALUES
(1   ,     1      ,      1     ,   15),
(2   ,     2      ,      1     ,   12),
(3   ,     2      ,      3     ,   19),
(4   ,     2      ,      5     ,   14),
(5   ,     4      ,      1     ,   12),
(6   ,     4      ,      2     ,   14),
(7   ,     4      ,      4     ,   13),
(8   ,     4      ,      5     ,   17),
(9   ,     5      ,      1     ,   18),
(10  ,     5      ,      6     ,   19),
(11  ,     5      ,      7     ,   15);

SELECT x.*
  FROM my_table x 
  JOIN my_table y 
    ON y.student_id = x.student_id 
   AND y.marks <= x.marks 
 GROUP  
    BY x.id 
HAVING COUNT(y.id) = 2;

+----+------------+------------+-------+
| id | student_id | subject_id | marks |
+----+------------+------------+-------+
|  4 |          2 |          5 |    14 |
|  7 |          4 |          4 |    13 |
|  9 |          5 |          1 |    18 |
+----+------------+------------+-------+