多对多有共同之处

时间:2018-09-14 06:01:08

标签: mysql sql many-to-many

+------+--------+---------+
| id   | teacher|student  |
+-------+-------+---------+
| 1    | 1      |1        |
| 2    | 3      |3        |
| 3    | 3      |4        |
| 4    | 3      |5        |
| 5    | 3      |6        |
| 6    | 4      |5        |
| 7    | 4      |6        |
+-------+-------+---------+

这是一个多对多关联表,我该如何查询他们有共同老师的学生列表,例如3 4?

我期望能够让学生5和6成为学生,因为他们都“共享”了同一位老师?

我目前拥有的是

SELECT ts.studentId, ts.teacherId FROM teacher_students ts group by ts.studentId, ts.teacherId having ts.teacherId in (3,4);

但是我要让学生3,4,5,6代替5,6

3 个答案:

答案 0 :(得分:2)

这是执行此操作的一种典型方法:

SELECT studentId
FROM teacher_students
WHERE teacherId IN (3, 4)
GROUP BY studentId
HAVING MIN(teacherId) <> MAX(teacherId);

enter image description here

Demo

上述查询的一个优点是它对索引友好。更一般而言,如果您希望学生说三个或三个以上的普通老师,则可以使用以下方法:

SELECT studentId
FROM teacher_students
WHERE teacherId IN (...)      -- some_num of teachers
GROUP BY studentId
HAVING COUNT(DISTINCT teacherId) = some_num;

答案 1 :(得分:1)

使用有条件的聚集地

 select studentId from teacher_students t
 where t.teacherId in (3,4)
 group by t.studentId
 having count(distinct t.teacherId )=2

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=70b3b2de9695f2f567afeaee7ec37bda

     studentId
       5
       6

答案 2 :(得分:0)

您还可以将where子句与exists一起使用:

SELECT ts.*
FROM teacher_students ts
WHERE teacherId IN (3,4) AND
      EXISTS (SELECT 1 
              FROM teacher_students ts1 
              WHERE ts.studentId = ts1.studentId AND ts.teacherId <> ts1.teacherId
             );