SQL查询(使用连接)/递归

时间:2012-07-24 14:12:51

标签: sql sql-server tsql join

我有3个表:AuditCheckCriteria为T1,学习者为T2& LearnerAuditRegistrations为T3,具有以下结构:

  T1: CheckID     CheckName                      
          1       'Stage One'
          2       'Stage Two'
          3       'Stage Three'

  T2   LearnerID   LearnerName
          10         'John'
          11         'Peter'
          12         'Paul'

  T3: LearnerAuditID  LearnerID  CheckID
          1             10         1
          2             10         2
          3             11         1
          4             11         2
          5             11         3

我想要以下输出:

T2.LearnerID, T1.CheckID, T3.CheckID
      10           1           1
      10           2           2
      10           3          NULL
      11           1           1
      11           2           2
      11           3           3
      12           1          NULL
      12           2          NULL
      12           3          NULL

(T2& T3每个包含超过20000行)

感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

看起来你想要T1和T2的所有值组合,以及来自T3的查找。如果是这样,以下是这样的:

with t1vals as (select distinct checkID from t1),
     t2vals as (select distinct LearnerId from t2)
select t2vals.LearnerId, t1vals.CheckId, t3.CheckId
from t1vals cross join
     t2vals left outer join
     t3
     on t3.LearnerId = t2vals.LearnerId and
        t3.CheckId = t1vals.CheckId

答案 1 :(得分:0)

使用(T2交叉连接T1)左连接T3 ..