又一次question I've made before。我想扩展查询表的数量。
情况是:
我们说我有3个数据库表:
因此,一些教师有一个共同的主题。
我已经考虑了用于查询的算法:
对于主题表中的每个记录:
在teachers_subjects表中选择计数 如果count大于1
在teacher_subjects中,获取teacher_id,其中subject_id是s。建立关系对。
我需要输出如下输出:
+----------+----------+-----------------------+----------------------------+
| Teacher1 | Teacher2 | NumberOfRelationships | SubjectsInCommon |
+----------+----------+-----------------------+----------------------------+
| Ian | Ralph | 4 | Math, Science, English, PE |
| Anna | Maria | 2 | Math, Trigonometry |
+----------+----------+-----------------------+----------------------------+
所以我在这个SQL查询中得到了答案:
SELECT @rownum := @rownum + 1 as id, relations.Teacher1, relations.Teacher2, relations.subjects, relations.count
FROM (SELECT t1.name as 'Teacher1', t2.name as 'Teacher2', GROUP_CONCAT(s.name) AS subjects, count(*) AS count
FROM teachers t1
JOIN teachers t2 ON t1.id > t2.id
JOIN teachers_subjects ts1 ON ts1.teacher_id = t1.id
JOIN teachers_subjects ts2 ON ts2.teacher_id = t2.id AND ts1.subject_id = ts2.subject_id
JOIN subjects s ON ts1.subject_id = s.id
GROUP BY ts1.teacher_id, ts2.teacher_id) as relations,
(SELECT @rownum := 0) r;
但是,如果我有更多的表格如下:
我希望获得如下输出:
+----------+----------+-------------------------+--------------------+
| Teacher1 | Teacher2 | NumOfTotalRelationships | ActivitiesInCommon |
+----------+----------+-------------------------+--------------------+
| | | | |
+----------+----------+-------------------------+--------------------+
如果我将来需要添加更多表格,无论如何它都适用于 n 表
答案 0 :(得分:1)
您可以尝试为低级别关系创建视图。然后你可以加入意见以获得任何关系。