如何在SQL中找到正在参加C课程的学生C的同学?

时间:2012-09-07 18:41:41

标签: sql union

有两个表,studentscoursesstudents表格包含nameagessn

CoursesssnCourse

现在ssn表中的courses并非唯一,但students中的C是主键。

我需要找出正在学习C学生正在学习的任何课程的学生(包括union的姓名)。

这是一个挑战问题,所以我可以不介意,但我想知道解决方案是什么。

到目前为止,我已尝试使用SELECT ssn FROM courses UNION SELECT ssn FROM students WHERE name = 'c' 运算符,如下所示:

courses

所有这一切都会返回表{{1}}中的所有ssns。该问题要求我们有效地找到两个表的集合UNION以确定解决方案。

感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

SELECT DISTINCT s2.ssn, s2.name
    FROM students s1
        INNER JOIN courses c1  /* Find all courses taken by student 'c' */
            ON s1.ssn = c1.ssn
        INNER JOIN courses c2  /* Find all students in all of c's courses */
            ON c1.course = c2.course
        INNER JOIN students s2 /* Get the details for each of those students */
            ON c2.ssn = s2.ssn
    WHERE s1.name = 'c'

答案 1 :(得分:0)

select distinct c1.ssn, s1.name from courses c1   // find distinct ssn and name for courses X (defined below)
inner join students s1 on c1.ssn=s1.ssn
where c1.course  in 
(select course
 from courses     // use to find all courses (say X) for student c
where ssn =
(select ssn from students where name='c'))  // find ssn of student

希望这有帮助