Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Erkennen von Beziehungen zwischen MySQL-DB-Einträgen

Probieren Sie dies aus (Sie sollten zum besseren Testen einige Beispieldaten in SQLFiddle laden)

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;