SQL Distinct Join

时间:2012-04-18 19:29:48

标签: sql sql-server-2008 join outer-join

我正在尝试加入另一个领域的独特领域。

示例:tbl.Class中有多个行分类在column.Teacher下,具有相同的值。我想在column.Teacher中加入一个DISTINCT值到另一个表中的column.Teacher_Course(tbl.Course)。

以下是我的想法,但不是只从tbl.Class中检索一个值,而是获得多个连接。

SELECT distinct(Teacher.JohnJoe)
FROM  tbl.Class

RIGHT OUTER JOIN tbl.Course ON Course.Teacher_Course = Class.Teacher  

2 个答案:

答案 0 :(得分:1)

您也可以尝试使用GROUP BY子句:

SELECT Teacher.JohnJoe
FROM  tbl.Class
RIGHT OUTER JOIN tbl.Course ON Course.Teacher_Course = Class.Teacher  
GROUP BY Teacher.JohnJoe

答案 1 :(得分:0)

简历:

  • tbl.Class中的多位老师
  • tbl.Course的单身教师
  • 结果应该从tbl.Class为tbl.Class中的每个记录提供一位教师

我的SQL解释:

DECLARE @class TABLE ([id] int, [teacher] nvarchar(20))
DECLARE @course TABLE ([id] int, [course] nvarchar(20), [teacher_course] nvarchar(20))

INSERT INTO @class ([id], [teacher]) VALUES (1, 'Teacher 1')
INSERT INTO @class ([id], [teacher]) VALUES (2, 'Teacher 2')
INSERT INTO @class ([id], [teacher]) VALUES (3, 'Teacher 3')
INSERT INTO @class ([id], [teacher]) VALUES (4, 'Teacher 4')
INSERT INTO @class ([id], [teacher]) VALUES (5, 'Teacher 1')

INSERT INTO @course ([id], [course], [teacher_course]) VALUES (1, 'Course 1', 'Teacher 1')
INSERT INTO @course ([id], [course], [teacher_course]) VALUES (2, 'Course 2', 'Teacher 4')

SELECT 
    [co].[id],
    [co].[course],
    [cl].[teacher]
FROM  @course [co]
INNER JOIN @class [cl] ON [co].[teacher_course] = [cl].[teacher]
GROUP BY
    [co].[id],
    [co].[course],
    [cl].[teacher]

结果是:

[id]  [course]  [teacher]
1     Course 1  Teacher 1
2     Course 2  Teacher 4