如果我的表格是这样设置的:
Apply: studentID, cName
Student: studentID, sName
如何在“应用”中有以下条目的学生中列出学生ID和sName:
Apply.studentID = Student.studentID AND Apply.cName = "College1"
AND
Apply.studentID = Student.studentID AND Apply.cName = "College2"
最终,我想做的是列出同时申请了cName为“ College1”和“ College2”的两所大学的学生。
答案 0 :(得分:1)
通过执行两个子查询,一个用于获取应用于College1的StudentID,另一个用于College2,您可以确保从Student返回的学生具有在两个子查询结果集中都存在的studentID。
SELECT sName
FROM Student
WHERE studentID IN (
SELECT DISTINCT studentID FROM Apply WHERE cName='College1'
)
AND studentID IN (
SELECT DISTINCT studentID FROM Apply WHERE cName='College2'
)
答案 1 :(得分:1)
您可以检查两个条件是否存在:
select * from Student s
where exists
(select * from Apply a where a.StudentId = s.StudentId and a.cName = 'College1') and
exists
(select * from Apply a where a.StudentId = s.StudentId and a.cName = 'College2');
答案 2 :(得分:0)
您可以使用CTE
来避免重复代码。
with
cte
as
(
select
studentID
from
[Apply]
where
cName in('College1', 'College2')
)
select
s.sName
from
cte
inner join
Student s
on
cte.studentID = s.studentID;