MySQL声明返回2名学生

时间:2017-03-06 10:16:55

标签: mysql sql

您好我想要一个可以返回所有课程的SQL语句 至少有2名学生注册,并按照课程顺序进行 最多的学生。我对SQL的东西很新,我发现它有点困难。

这是我当前的数据库

wget https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64
chmod +x jq-linux64
sudo mv jq-linux64 $(which jq)

这就是我试过的

 CREATE TABLE `course` (
      `CourseID` char(11) NOT NULL,
      `Course_name` varchar(22) DEFAULT NULL,
      `hours_per_week` varchar(22) DEFAULT NULL,
      `Start_date` date DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `course`
    --

    INSERT INTO `course` (`CourseID`, `Course_name`, `hours_per_week`, `Start_date`) VALUES
    ('C001', 'Cert 1', '15', '2012-02-01'),
    ('C002', 'Cert 2', '20', '2012-02-02'),
    ('C003', 'Cert 3', '16', '2012-02-03'),
    ('C004', 'Cert 4', '20', '2012-02-13');

    -- --------------------------------------------------------

    --
    -- Table structure for table `enrolment`
    --

    CREATE TABLE `enrolment` (
      `studentID` char(11) NOT NULL,
      `courseID` char(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `enrolment`
    --

    INSERT INTO `enrolment` (`studentID`, `courseID`) VALUES
    ('S001', 'C001'),
    ('S002', ' C001'),
    ('S003', ' C002'),
    ('S004', ' C002'),
    ('S005', ' C004');

    -- --------------------------------------------------------

    --
    -- Table structure for table `student`
    --

    CREATE TABLE `student` (
      `StudentID` char(11) NOT NULL,
      `FirstName` varchar(22) DEFAULT NULL,
      `LastName` varchar(22) DEFAULT NULL,
      `DOB` date DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `student`
    --

    INSERT INTO `student` (`StudentID`, `FirstName`, `LastName`, `DOB`) VALUES
    ('S001', 'Alison', 'Tildesley', '1984-05-09'),
    ('S002', 'Fred', 'Nile', '1940-03-03'),
    ('S003', 'Christine', 'Anu', '1970-09-01'),
    ('S004', 'Jame', 'Brown', '1976-02-03'),
    ('S005', 'Mark', 'Oliphant', '1958-03-10'),
    ('S006', 'George', 'Bush', '1951-11-28');

我知道我必须在课程表中添加SELECT FROM COURSES WHERE STUDENT_ID >=2 行,但我仍然对如何获得所需结果感到困惑。对不起,我对数据库和MYSQL语句都很陌生。

2 个答案:

答案 0 :(得分:1)

这应该做:

SELECT C.CourseID, C.Course_name, COUNT(E.StudentID) Students_num
FROM course C
JOIN enrolment E USING(CourseID)
GROUP BY C.CourseID, C.Course_name
HAVING Students_num >= 2
ORDER BY Students_num DESC, C.Course_name

这将提取所有与其注册记录相关的课程,然后按课程ID和名称分组,计算学生人数;最后一个HAVING子句将丢弃所有记录,这些记录在分组后将少于2名学生。

这是一个用于测试的working SQL fiddle

答案 1 :(得分:0)

未经测试;)

select 
    c.courseID, count(0)
from course c, enrolment e 
where c.CourseID = e.CourseID
group by 
    c.courseID
having
    count(0) >= 2
order by 
    count(0) desc