0

我有两个表,除了 1 之外,它们具有相同的列。例如:

Table1 (column names): Student | Course | Exam1 | Exam2
Table2 (column names): Student | Course | Exam3 | FinalExam

我想将这两个表结合起来得到:

Table: Student | Course | Exam1 | Exam2 | FinalExam

我有以下几点:

Select
    student,
    course,
    Exam1, 
    Exam2
From Table1

Select
    student,
    course,
    Exam3, 
    FinalExam
From Table2


Select
    student,
    course,
    Coalesce( t1.Exam1, 0) as Exam1 
    Coalesce( t1.Exam2, 0) as Exam2
    Coalesce( t2.Exam3, 0) as Exam3
    Coalesce( t2.FinalExam, 0) as FinalExam
From Table1 t1, Table2 t2

有没有办法使用内部连接更有效/更简洁地做到这一点?

4

2 回答 2

2

你所做的是一个有 n*n 行的笛卡尔积。

试试这个

Select
    student,
    course,
    Exam1,
    Exam2,
    Exam3,
    FinalExam,
From Table1 t1, Table2 t2
Where t1.student=t2.student
and t1.course=t2.course;

此查询适用于学生至少参加了考试 1 或 2 以及考试 3 或期末考试的情况。如果有可能缺席的情况,则需要使用外连接。像下面的例子,但不限于

Select
    student,
    course,
    Exam1,
    Exam2,
    Exam3,
    FinalExam,
From Table1 t1, Table2 t2
Where t1.student=t2.student(+)
and t1.course=t2.course(+);
于 2013-09-16T20:10:06.887 回答
1

根据您的问题的一些假设,这是我认为 您想要的。

 select isnull(t1.student, t2.student),  isnull(t1.course, t2.course),
    IsNull( t1.Exam1, 0) as Exam1 ,
    IsNull( t1.Exam2, 0) as Exam2,
    IsNull( t2.Exam3, 0) as Exam3,
IsNull( t2.FinalExam, 0) as FinalExam
From Table1 t1 
   full outer join  Table2 t2 
        on t1.student = t2.student 
            and t1.course = t2.course
于 2013-09-16T20:18:14.220 回答