查询获取学生和成绩SQL

时间:2017-12-12 20:23:23

标签: mysql sql

我有一个学生表学生(LRN,fName,lName,levelID)和一个成绩表GRADE(subjectID,年级,levelID,LRN,TimeAdded)我想向所有学生展示所有在线成绩的学生。我厌倦了这个查询,但我得到了这个结果。

Query: SELECT student.LRN, student.fName, student.lName, 
(SELECT grade.grade WHERE grade.subjectID = 'k2arts') AS 'k2arts',
(SELECT grade.grade WHERE grade.subjectID = 'k2math') AS 'k2math',
(SELECT grade.grade WHERE grade.subjectID = 'k2eng') AS 'k2eng',
(SELECT grade.grade WHERE grade.subjectID = 'k2valed') AS 'k2valed',
(SELECT grade.grade WHERE grade.subjectID = 'k2fil') AS 'k2fil' 
from student RIGHT JOIN grade on grade.LRN=student.LRN 

结果: Query Result

3 个答案:

答案 0 :(得分:0)

您希望在每个子查询中建立STUDENT的关系。您不需要在主查询中加入Grade,因为您不使用任何值,除非通过子查询,在这种情况下处于不相关的上下文中:

SELECT student.LRN, student.fName, student.lName, 
(SELECT grade.grade FROM grade WHERE grade.subjectID = 'k2arts' AND grade.LRN=st.LRN) AS 'k2arts',
(SELECT grade.grade FROM grade WHERE grade.subjectID = 'k2math' AND grade.LRN=st.LRN) AS 'k2math',
(SELECT grade.grade FROM grade WHERE grade.subjectID = 'k2eng' AND grade.LRN=st.LRN) AS 'k2eng',
(SELECT grade.grade FROM grade WHERE grade.subjectID = 'k2valed' AND grade.LRN=st.LRN) AS 'k2valed',
(SELECT grade.grade FROM grade WHERE grade.subjectID = 'k2fil' AND grade.LRN=st.LRN) AS 'k2fil' 
from student st 

答案 1 :(得分:0)

您可以使用左连接和

时的情况
SELECT student.LRN, student.fName, student.lName, 
  case when grade.subjectID = 'k2arts' then grade.grade else null end AS 'k2arts',
  case when grade.subjectID = 'k2math' then grade.grade else null end AS 'k2math',
  case when grade.subjectID = 'k2eng' then grade.grade else null end AS 'k2eng',
  case when grade.subjectID = 'k2valed' then grade.grade else null end AS 'k2valed',
  case when grade.subjectID = 'k2fil' then grade.grade else null end AS 'k2fil'
from student 
LEFT JOIN grade on grade.LRN=student.LRN 

并最终使用伪聚合函数删除null

SELECT student.LRN, student.fName, student.lName, 
  min(case when grade.subjectID = 'k2arts' then grade.grade else null end) AS 'k2arts',
  min(case when grade.subjectID = 'k2math' then grade.grade else null end) AS 'k2math',
  min(case when grade.subjectID = 'k2eng' then grade.grade else null end) AS 'k2eng',
  min(case when grade.subjectID = 'k2valed' then grade.grade else null end) AS 'k2valed',
  min(case when grade.subjectID = 'k2fil' then grade.grade else null end) AS 'k2fil'
from student  student.LRN, student.fName, student.lName
LEFT JOIN grade on grade.LRN=student.LRN 
group by 

答案 2 :(得分:0)

尝试:

SELECT student.LRN, student.fName, student.lName, 
CASE WHEN grade.subjectID = 'k2arts' THEN grade.grade END AS 'k2arts',
CASE WHEN grade.subjectID = 'k2math'  THEN grade.grade END AS 'k2math',
CASE WHEN grade.subjectID = 'k2eng'   THEN grade.grade END AS 'k2eng',
CASE WHEN grade.subjectID = 'k2valed' THEN grade.grade END AS 'k2valed',
CASE WHEN grade.subjectID = 'k2fil'   THEN grade.grade END AS 'k2fil' 
from student 
LEFT JOIN grade 
on grade.LRN=student.LRN ;