Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        5年前关闭。
                                                                                            
                
        
我有一个像下面的桌子。我只想获取所有学生的第二低分数科目(基于分数的升序)。请帮我查询。

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

最佳答案

您可以使用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;


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

关于mysql - MySQL查询获取表中所有学生的第二低的分数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27544452/

10-13 01:54