SQL在另一个表中查找列的所有值

时间:2011-03-22 12:49:12

标签: sql compare

好的,我有一张桌子,里面有学生证和课程。 比如

00001 CS-543
00001 CS-145
00002 HIST-123
... etc.

我有一些课程ID列;我们称之为B,

CS-123
... etc.

我想搜索所有参加B课程的学生。我怎么能为此写一个查询?

3 个答案:

答案 0 :(得分:1)

SELECT A.StudentID
FROM A
  INNER JOIN B ON A.CourseID = B.CourseID
GROUP BY A.StudentID
HAVING COUNT(DISTINCT A.CourseID) >= COUNT(DISTINCT B.CourseID)

答案 1 :(得分:0)

SELECT DISTINCT STUDENT FROM A WHERE STUDENT NOT IN
(
  SELECT STUDENT FROM
  (
    SELECT *
    FROM 
     (SELECT DISTINCT STUDENT FROM A) AS ALLSTUDENTS 
     CROSS JOIN B  
    EXCEPT 
    SELECT * FROM A
  ) AS INCOMPLETE
)

答案 2 :(得分:-1)

使用IN子句:

SELECT * FROM B WHERE B.CourseID IN (SELECT CourseID FROM A)

这将为您提供B中出现在A

中的所有记录