从与另一个表关联的表中删除重复项

时间:2016-11-09 09:20:52

标签: mysql sql database

Student
_______________________
SudentId   Name
101        Peter
103        John
112        James
116        Peter
117        Peter


SudentId_Subject
_______________________
SudentId Subject
101      Physics
103      Chemistry
112      Mathematics
116      Physics
117      Commerce

为了找到重复的学生,我尝试了查询

select * from Student group by Name having count(*)>1

SudentId   Name
_______________________
101        Peter
116        Peter
117        Peter

实际上我需要过滤同一主题的学生。即,

101        Peter
116        Peter

是重复的(同一主题)但不是117 Peter

如何为此编写查询?

2 个答案:

答案 0 :(得分:3)

我可能有过复杂的事情,但无法想到更简单的方法:

SELECT ss.student_id,ss.name
FROM student ss
JOIN studentid_subject tt
 ON(ss.student_id = tt.student_id)
JOIN(SELECT t.name,s.department
     FROM student t
     JOIN studentid_subject s
      ON(t.student_id = s.student_id)
     GROUP BY t.name,s.department
     HAVING COUNT(*) > 1) p
 ON(ss.name = p.name and tt.department = p.department)

答案 1 :(得分:-1)

从学生左侧选择*加入关于Student.SudentId = SudentId_Subject.DepId的SudentId_Subject,其中Student.SudentId = SudentId_Subject.DepId