Mysql
 sql >> Base de données >  >> RDS >> Mysql

Détecter les relations entre les enregistrements de base de données MySQL

Essayez ceci (vous devriez charger des exemples de données dans SQLFiddle pour un meilleur test)

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;