基于他们教授多少相似课程的教师比较

时间:2016-11-18 01:53:25

标签: mysql sql phpmyadmin

我有这段代码:

{{1}}

This is the output of said code

我需要做的是比较两个名字,看看它们有多少个共同的课程代码。 (例如:asifa amir和stephen cheung都教授一个BUSI课程,因此,我们在一个" coteaches" count。中添加一个。

输出必须是:

teacher1Name,teacher2Name,numberOfCoteaches

但我不能为我的生活找出如何做出这样的输出。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这将为每对教师提供他们共享的课程代码数量。

SELECT a.name name1, b.name name2, 
    count(distinct substring(seb.course,1,4)) coteaches
FROM (instructors a 
       Join teaches ta on ta.instructor_id = a.instructor_id
       Join schedules sha on sha.id = ta.ScheduleId
       Join sections sea.id = sha.sectionId)
   join (instructors b
       Join teaches tb on tb.instructor_id = b.instructor_id
       Join schedules shb on shb.id = tb.ScheduleId
       Join sections seb on seb.id = shb.sectionId)
      on substring(seb.course,1,4) = substring(sea.course,1,4)
Group By a.name, b.name 

要仅为一对特定教师执行此操作,请添加限制输出的where子句

Where a.Name = [Put one name here]
  and b.name = [Put the other name here]

答案 1 :(得分:0)

这是一个自我加入,但这是一个真正的痛苦。为什么teaches表没有自己的课程?

SELECT t1.instructor_id, t2.instructor_id, count(*)
FROM teaches t1 JOIN
     schedules s1
     ON t1.schedule_id = s1.id JOIN
     sections sec1
     ON s1.section_id = sec1.id JOIN
     sections sec2
     ON sec2.course_id = sec1.course_id JOIN
     schedules s2
     ON s2.section_id = sec2.id JOIN
     teaches t2
     ON t2.schedule_id = s2.id AND
        t1.instructor_id < t2.instructor_id 
GROUP BY t1.instructor_id, t2.instructor_id;

由于对CTE的支持,这在几乎任何其他数据库中都更容易编写和更直观。

答案 2 :(得分:0)

假设您已经拥有的查询生成表t,则以下查询将生成结果。

SELECT t1.name1, t2.name1), COUNT(1)
FROM t AS t1 JOIN t AS t2 ON t1.courseCode = t2.courseCode
WHERE t1.name1 != t2.name1
GROUP BY t1.name1, t2.name1
ORDER BY COUNT(1) DESC

唯一需要注意的是,它为每对教师生成了2行,因为teacher1,teacher2teacher2,teacher1是不同的元组。

尝试使用SET语句中的SELECT type来避免这种情况。