简体   繁体   中英

mysql select record that have two rows

If I have a student_table as follows:

original_student            other_student
10123                       20234    
10234                       20456 

And I have other table containing student class

Student_code                Class
10123                       class_001
20234                       class_002     
10234                       class_003
20456                       class_004

My question is for the student_table, how can I find out that the total count of class is greater than or equal to 2 for the row of original_student and other_student, I need to count by combining the original_student and other_student.

thanks

select s.original_student, s.other_student, count(*) 
from student_table s      
inner join student_class c1 on c1.Student_code = s.original_student
inner join student_class c2 on c2.Student_code = s.other_student
group by s.original_student, s.other_student
having count(*) >= 2

You can do it with a single join using an IN(...) join condition:

select s.original_student, s.other_student, count(distinct sc.class) 
from student_table s      
join student_class sc on sc.Student_code in (s.original_student, s.other_student)
group by s.original_student, s.other_student
having count(distinct sc.class) > 1

The distinct is used in the count() in case each student is is associated with the same class code, which (probably) shouldn't count as two classes but rather just the one class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM