2016-07-05 180 views
0

我有一個Students表和一個語言表。它們使用數據透視表Languages_Student形成多對多的關係。Count()對多對多關係

有沒有辦法讓學生的語言與其他學生有最多的共同點?

我不太清楚如何將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 

我試圖獲得與ID爲65

任何想法的學生的常用語言最大金額的學生嗎?

回答

0

您可以使用自連接來完成此操作。在語言列中加入交叉表本身;然後聚集在學生列,以獲得數共同點:

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; 
+0

是的!謝謝! –

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)