获取table1中但不在table2中的行

时间:2012-06-15 07:37:20

标签: sql-server

我有两张桌子,

CREATE TABLE [dbo].[entry]
(
   [id] [int] NULL,
   [service] [int] NULL,
   [sub] [int] NULL
) 

值是,

id     service  sub
1        1       0
2        1       1 
3        1       2 

第二张表是:

CREATE TABLE [dbo].[service]
(
   [service] [int] NULL,
   [sub] [int] NULL
) 

及其值为:

service   sub
1          0
1          1

entry表中有3行,service表中有两行。我想要不在service表中但在entry

中的行

由于

Venkat

4 个答案:

答案 0 :(得分:1)

试试这个:

Select entry.id, temp.service, temp.sub from entry INNER JOIN 
(Select service, sub from entry 
Except
Select service, sub from service) as temp ON entry.service = temp.service AND entry.sub = temp.sub

答案 1 :(得分:0)

解决问题的另一种方法

  Select a.id,a.service,a.sub from @entry as a where not EXISTS 
 (select b.* from @service as b where a.sub = b.sub and a.service=b.service)

答案 2 :(得分:0)

使用除了。

之外的代码的另一种变体
select id, service, sub
from entry
except
select e.id, e.service, e.sub
from service as s left join entry as e
on s.service = e.service
and s.sub = e.sub

答案 3 :(得分:0)

SELECT
    entry.id
  , entry.service
  , entry.sub
FROM
    entry
LEFT JOIN SERVICE ON entry.service = service.service AND entry.sub = service.sub
WHERE
    entry.service IS NULL
    AND entry.sub IS NULL