如何使用两个表

时间:2016-12-14 07:16:56

标签: sql sql-server

我有两张如下表:

表1

id  name    enrollno    subjectname batchname   groupname
1   abc       a1          s1          b1            g1
2   xyz       a2          s1          b2            g1

表2

sid subjectname batchname   groupname
1   s1          b1          g1
2   s2          b2          g1

我想从Table 1获取与TABLE 2中的任何记录都不匹配的记录,如下所示

name    groupname   batchname   subjectname
xyz     g1          b2           s1

由于

2 个答案:

答案 0 :(得分:2)

使用NOT EXISTS

SELECT *
FROM   table1 t1
WHERE  NOT EXISTS(SELECT 1
                  FROM   table2 t2
                  WHERE  t2.subjectname = t1.subjectname
                         AND t2.batchname = t1.batchname
                         AND t2.groupname = t1.groupname); 

答案 1 :(得分:0)

您可以在此处使用LEFT JOIN

SELECT t1.name,
       t1.groupname,
       t1.batchname,
       t1.subjectname
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.subjectname = t2.subjectname AND
       t1.batchname   = t2.batchname AND
       t1.groupname   = t2.groupname
WHERE t2.subjectname IS NULL

如果table2中的连接列设置了索引,则这可能具有速度优势。