有两个表,students
和courses
。 students
表格包含name
,age
和ssn
。
Courses
有ssn
和Course
。
现在ssn
表中的courses
并非唯一,但students
中的C
是主键。
我需要找出正在学习C
学生正在学习的任何课程的学生(包括union
的姓名)。
这是一个挑战问题,所以我可以不介意,但我想知道解决方案是什么。
到目前为止,我已尝试使用SELECT ssn
FROM courses
UNION SELECT ssn
FROM students
WHERE name = 'c'
运算符,如下所示:
courses
所有这一切都会返回表{{1}}中的所有ssns。该问题要求我们有效地找到两个表的集合UNION以确定解决方案。
感谢任何帮助!
答案 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
希望这有帮助