sql >> Base de Datos >  >> RDS >> Mysql

Detección de relaciones entre registros de base de datos MySQL

Pruebe esto (debe cargar algunos datos de muestra en SQLFiddle para una mejor prueba)

SELECT t1.`name` AS teacher1, t2.`name` AS teacher2, count(*)
FROM teachers AS t1
JOIN teachers AS t2
  ON t1.id > t2.id
JOIN teacher_subjects AS ts1
  ON ts1.teacher_id = t1.id
JOIN teacher_subjects AS ts2
  ON ts2.teacher_id = t2.id
    AND ts2.subject_id = ts1.subject_id
GROUP BY teacher1, teacher2
ORDER BY COUNT(*) DESC;