SQL语句从两个表中选择where

时间:2012-12-09 09:29:09

标签: asp.net sql sql-server-2008

我有两个表定义如下:

课程

course ID     course Name
1             Math
2             Science
3             geography

和另一张表(其用途是显示在课程中注册的学生):

student_courses

course ID     student ID      Final cost
1             2               100
2             3               200

我需要一个SQL语句,它只选择某个学生的课程(它的值是我页面上控件的参数 - 但这不是我的问题)没有注册....

我最近的尝试是:

SELECT 
   Courses.[Course ID], Courses.[Course name] 
FROM 
   Courses, student_courses 
where 
   Courses.[Course ID] <> student_courses.[Course ID]

3 个答案:

答案 0 :(得分:4)

你只需要这样的东西:

SELECT
    c.[Course ID], c.[Course Name]
FROM
    dbo.Course c
WHERE
    NOT EXISTS (SELECT * FROM dbo.StudentCourses sc
                WHERE [Student ID] = 2 AND [Course ID] = c.[Course ID])

请参阅my SQL Fiddle showing this

基本上,只需选择那些Student_Courses中没有[Student ID]

条目的课程

答案 1 :(得分:3)

SELECT [Course ID], [Course name] 
FROM Courses
WHERE [Course ID] NOT IN 
 (SELECT Course ID from student_courses WHERE [student ID]=1) 

答案 2 :(得分:1)

我能想到的最简单的(Transact)SQL是:

select 
     [courses].[course ID]
   , [courses].[course name]
from [courses]
left outer join [student_courses]  
       on   [student_courses].[course ID]  = [courses].[course ID] 
       and  [student_courses].[student ID] = @studentID
where 
     [student_courses].[student ID] is null

不要在where子句中放置“[student_courses]。[student ID] = @studentID”,因为这会导致您感兴趣的空值被丢弃而您的左连接将看起来就像一个内部联接。

如果你想要不必要的复杂,你可以使用组,拥有和计数。

select 
    [courses].[course ID]
  , [courses].[course name]
from [courses]
left outer join [student_courses]  
           on   [student_courses].[course ID]  = [courses].[course ID] 
           and  [student_courses].[student ID] = @studentID
group by
     [courses].[course ID]
   , [courses].[course name]
having count([student_courses].[course ID]) = 0

从列名中丢失空格可能是个好主意。从长远来看,这只会给你带来麻烦。