加入查询对表中的所有元素无法正常工作

时间:2017-12-13 14:50:24

标签: mysql join mariadb

这是我的问题,我有两个表科目和成绩。

  CREATE TABLE `grades` (
  `gradesID` int(11) NOT NULL,
  `studentBook` int(11) DEFAULT NULL,
  `subjectID` varchar(5) DEFAULT NULL,
  `grade` int(5) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `grades` (`gradesID`, `studentBook`, `subjectID`, `grade`) VALUES
(1, 1034, 'AD356', 9),
(2, 1034, 'CS102', 10),
(3, 1034, 'CS103', 9),
(4, 1034, 'CS220', 5)

CREATE TABLE `subjects` (
  `subjectID` varchar(5) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `espb` smallint(6) DEFAULT NULL,
  `number_of_classes_per_week` smallint(6) DEFAULT NULL,
  `number_of_practices_per_week` smallint(6) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `subjects`
--

INSERT INTO `subjects` (`subjectID`, `name`, `espb`, `number_of_classes_per_week`, `number_of_practices_per_week`) VALUES
('AD356', '3D modeling Maya', 10, 3, 3),
('CS101', 'Introduction to object-oriented programming', 10, 3, 4),
('CS102', 'JAVA 2', 10, 3, 4),
('CS103', 'Algorithms', 8, 3, 3),

我需要进行加入查询以查找所有试图参加考试的学生的数量(无论他们通过或失败)。我需要显示结果: subjects.subjectID,subjects.name,每个科目的课程和练习的总数,参加考试的学生人数(无论是通过还是失败)。 所以这是我的尝试:

SELECT 
  subjects.subjectID,
  subjects.name,
  (subjects.number_of_classes_per_week+subjects.number_of_practices_per_week) AS 'Totall number of classes per week',
  COUNT(grades.subjectID) AS 'Number of students that tried to pass'
FROM 
  subjects,
  grades 
WHERE 
  subjects.subjectID = grades.subjectID AND 
  grade >= 5;

但是我只得到第一个主题ID,该主题的课程数量和所有科目的学生总数 我想拥有的结果是这样的:

subjectID     name                           Totall number of classes per week                      Number of students that tried to pass
AD356    3D modeling Maya                  6              10
CS101   Introduction to object-oriented programming 7      4
CS102  'JAVA 2'                            7               5   
CS103    Algorithms                        6               4

2 个答案:

答案 0 :(得分:1)

你需要告诉MySQL要计算什么 - 换句话说,哪个字段应该用作分组标识符来计算。

在您的情况下,这将是subjectID,因为您想要计算每个科目的所有成绩(等级大于或等于5)。

所以你需要在WHERE语句之后添加:

GROUP BY subjectID

然后你应该完成。

答案 1 :(得分:1)

您正在使用count()聚合函数而没有group by,因此mysql只返回一行。试试这个(它可能对你有帮助):

SELECT 
  subjects.subjectID,
  subjects.name,
  (subjects.number_of_classes_per_week+subjects.number_of_practices_per_week) AS 'Totall number of classes per week',
  COUNT(distinct grades.studentBook) AS 'Number of students that tried to pass'
FROM 
  subjects
JOIN grades ON grades.subjectID = subjects.subjectID
GROUP BY subjects.subjectID