您可以用自聯接做到這一點:
select c1.student, c2.student, c1.class
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.student < c2.student;
如果兩個學生參加多類在一起,這將每類返回一行。
如果您在表中使用id
s而不是名稱(一個好主意),那麼您需要加入其他表的相應信息。我會留給你的。
編輯:
要計算的班兩名學生曾一起數,你可以使用group by
:
select c1.student, c2.student, count(*) as NumClasses
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.student < c2.student
group by c1.student, c2.student;
您可以使用having
條款通過count(*)
進行過濾。您可以將其加入其他表格以獲取特定的課程。
這裏是你如何加入該回到原來的表:
select s1.name as student1, s2.name as student2, count(*) as NumClasses
from ClassStudents c1 join
ClassStudents c2
on c1.class = c2.class and
c1.studentid < c2.studentid join
Students s1
on c1.studentid = s1.studentid join
Students s2
on c2.studentid = s2.studentid
group by c1.name, c2.name
having count(*) > 1;
你也可以做到這一點作爲一個子查詢,但是這是很容易做到。
什麼是您未來的查詢輸入? –
理想情況下,如果我可以讓所有回到課堂的學生一起上課,那麼沒有理由。但是,可以選擇提供student1和student2。 – endyourif