简体   繁体   English

SQL-基于同一表中的多个条目进行选择?

[英]SQL - Selecting based on multiple entries in same table?

If my tables are setup like this: 如果我的表是这样设置的:

Apply: studentID, cName

Student: studentID, sName

How can I list studentID and sName from Student where there are entries in Apply that have: 如何从“学生”中列出“学生ID”和“ sName”,其中“应用”中有以下条目:

Apply.studentID = Student.studentID AND Apply.cName = "College1"

AND

Apply.studentID = Student.studentID AND Apply.cName = "College2"

Ultimately, what I am trying to do is list the students that have applied to both colleges with cNames "College1" and "College2".. 最终,我想做的是用cNames“ College1”和“ College2”列出同时申请这两家大学的学生。

By doing two subqueries, one to get the studentIDs that applied to College1 and another for College2 you can ensure that the students returned from Student have studentIDs that exist in both of the subquery result sets. 通过执行两个子查询,一个获得适用于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'
)

You can check if it EXISTS with both criteria: 您可以检查两个条件是否存在:

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');

You can use CTE to avoid duplicated codes. 您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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