从一个表中选择在另一个表中多次出现的元素

时间:2016-03-25 11:56:48

标签: mysql sql inner-join

我需要找出已经注册至少两门课程的学生的姓名。

创建两个表:

CREATE TABLE Student (
  StudentID varchar(20) PRIMARY KEY,
  FirstName varchar(15),
  LastName varchar(30),
  Sex varchar(6),
  DOB date,
  Email varchar(40)
);

CREATE TABLE Enrols (
  StudentID varchar(20),
  CourseID varchar(20),
  CONSTRAINT Student_Course PRIMARY KEY (StudentID,CourseID),
  FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
  FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);

我的(不成功)尝试:

SELECT DISTINCT Student.FirstName,
  Student.LastName,
  Enrols.CourseID,                  
  COUNT (Student.FirstName) AS NumberOfNames
  FROM Student
  INNER JOIN Enrols
    ON Student.StudentID = Enrols.StudentID
  WHERE COUNT(Student.Firstname) >= 2;

4 个答案:

答案 0 :(得分:0)

您应该使用HAVINGGROUP BY(但如果您使用分组,则不应使用curseID)

SELECT Student.FirstName AS "First Name",
  Student.LastName AS "Last Name",          
  COUNT (*) AS "Number of Names"
  FROM Student
  INNER JOIN Enrols
    ON Student.StudentID = Enrols.StudentID
  HAVING COUNT(Student.Firstname) >= 2
  GROUP BY Student.FirstName, Student.LastName; 

答案 1 :(得分:0)

代替where,您可以使用group byhaving子句的组合,如下所示 -

SELECT Student.FirstName,
       Student.LastName,
       Student.StudentID,
       COUNT(CourseID) AS NumberOfCourceEnroll
  FROM Student
 INNER JOIN Enrols
    ON Student.StudentID = Enrols.StudentID
 group by Student.FirstName, Student.LastName, Student.StudentID
having COUNT(CourseID) >= 2;

你应该按studentId进行分组,因为这是学生主表中的主键。

答案 2 :(得分:0)

SELECT DISTINCT s.*
           FROM student s
           JOIN enrols x
             ON x.studentid = s.studentid
           JOIN enrols y
             ON y.studentid = x.studentid
            AND y.courseid < x.courseid;

答案 3 :(得分:0)

SELECT Student.FirstName AS "First Name",
  Student.LastName AS "Last Name",
  Enrols.CourseID AS "Course ID",
  COUNT(Student.FirstName) AS "Number of Names" 
  FROM Student
  INNER JOIN Enrols
    ON Student.StudentID = Enrols.StudentID  
  GROUP BY Student.FirstName
  HAVING COUNT(Student.FirstName) >= 2;

可行,但您只会看到一个CourseId。您不需要DISTINCT