Count()关于多对多的关系

时间:2016-07-05 18:54:50

标签: sql sql-server count group-by

我有学生表和语言表。它们使用数据透视表Languages_Student形成多对多的关系。

有没有办法让学生拥有与其他学生最多的语言?

我不太确定如何将COUNT()与某种选择结合起来。这就是我现在正在使用的:

select * from students student1
inner join languages_student ls1
    on student1.id = ls1.student_id
inner join languages l1
    on l1.id = ls1.language_id
inner join languages_student ls2
    on l1.id = ls2.language_id
inner join students student2
    on ls2.student_id = student2.id
where student1.id = 65
group by 16

我正在努力让这名学生与身份65的学生共同拥有最多的语言。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用自联接来执行此操作。在语言列上将联结表加入其自身;然后由 student 列汇总以获得共同的数字:

select ls.student_id, count(*) as NumInCommon
from languages_student ls join
     languages_student ls65
     on ls.language = ls65.language and ls65.student_id = 65 and
        ls65.student_id <> ls.student_id
group by ls.student_id
order by count(*) desc;

答案 1 :(得分:0)

        select  ls.student_id, count(ls.language_id) as common
        from languages_student ls
        where ls.id in (        
              select  l.id
              from students s
              inner join languages_student ls
              on s.id = ls.student_id
              inner join languages l
              on l.id = ls.language_id
              where s.id = 65 ) 
        order by count(ls.language_id)