教师表:
+----+------------+
| ID | Name |
+----+------------+
| 1 | TeacherOne |
| 2 | TeacherTwo |
+----+------------|
StudentTable:
+----+------------+
| ID | Name |
+----+------------+
| 1 | StudentOne |
| 2 | StudentTwo |
+----+------------+
Teacher_Student(Junction Table):
+-----------+-----------+
| TeacherID | StudentID |
+-----------+-----------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
+-----------+-----------+
我想要的是只选择TeacherID
,其中有StudentID
的记录与StudentID
为1且TeacherID
为2.在这种情况下,这只会给我{ {1}}是1。
我已经尝试过以下SQL语句:
SELECT t_s.*
FROM Teacher_Student AS t_s
WHERE StudentID IN (1, 2)
这会返回任何StudentID
为1或2的记录。我已经找到了答案但是找不到任何对我有帮助的东西,所以要求作为最后的手段。
答案 0 :(得分:1)
如果您想为每位学生选择在TeacherID
表中有记录的Teacher_Student
;你可以使用这个查询:
SELECT ts.TeacherID
FROM (
SELECT TeacherID, COUNT(StudentID) AS cnt
FROM teacher_student
GROUP BY TeacherID) ts
JOIN (
SELECT COUNT(*) As sCnt
FROM student) s
ON ts.cnt = s.scnt
<强> SQL Fiddle Demo 强>
您可以使用此查询选择两个特定学生:
SELECT ts.TeacherID
FROM (
SELECT TeacherID, COUNT(StudentID) AS cnt
FROM teacher_student
WHERE StudentID IN (1,2)
GROUP BY TeacherID) ts
WHERE cnt = 2
这也将删除与学生有两个联系的教师。