2011-12-16 43 views
1

假設我們有表SP(sid,pid),它顯示學生sid涉及項目pid。 現在我想MySQL查詢,選擇所有對誰在一個項目至少涉及學生,和他們在合作項目的數量用於查找圖中邊緣權重的MySQL查詢

例如:
輸入:
S1     P1
S1     P2
S2     P1
S3     P1
S4     P1
S4     P2

輸出:

S1     S2   S1     S3   S1     S4   S2     S3   S2     S4   S3     S4  

+0

這是功課?如果是,將其標記爲`[作業]`。 – 2011-12-16 19:06:12

+0

不,不是。研究問題。 – 2011-12-19 05:48:21

回答

5

Eric的回答可能會有點好轉:

select 
    sp1.sid as sid1, 
    sp2.sid as sid2, 
    count(*) as num 
from 
    sp as sp1 
    inner join sp as sp2 on sp1.pid=sp2.pid and sp1.sid<sp2.sid 
group by sp1.sid, sp2.sid 
; 

使用<,而不是<>避免歌廳(1,4,2)和(4,1,2)

1

這是做這件事的一個不同的方式。

select sid, sid2, count(*) from (
select sp.sid, second_student.sid as sid2,sp.pid from sp 
    join sp as second_student where sp.pid = second_student.pid and sp.sid < second_student.sid) as students 
    group by sid, sid2; 
+0

爲什麼是子查詢?這不是必需的。 – 2011-12-16 19:09:53

+0

謝謝!它工作完美:) – 2011-12-19 05:47:37

1

將表與自身:

select 
    s1.StudentId, 
    s2.StudentId, 
    Count(1) as ProjectCount 
from 
    StudentProjects s1 
    inner join StudentProjects s2 on 
     s1.ProjectId = s2.ProjectId 
     and s1.StudentId <> s2.StudentId 
group by s1.StudentId, s2.StudentId 

這裏的連接條件是在項目都是一樣的,但學生不是他或她自己。但是,這將過濾掉學生自己製作的任何項目。如果這對你很好,那我們就很好。如果不是,那麼您將需要使用left join代替inner join,但具有相同的連接條件。