Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Detectando relacionamentos entre registros de banco de dados MySQL


Tente isso (você deve carregar alguns dados de exemplo no SQLFiddle para um melhor teste)
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;