来自同一个表的2个SQL查询之间的差异

时间:2017-05-02 14:51:32

标签: sql

表SECURITYGROUPSID:

GROUPNAME    |    SIDNAME    
--------------------------
Group 1           Apple
Group 1           Apples
Group 1           Applesauce
Group 1           Applesauces
Group 1           Appleton
Group 2           Apple
Group 2           Applesauce
Group 2           Appleton

对于像'Apple%'这样的值,我需要第1组和第2组之间SIDNAME值的差异。例如,如果我执行以下2个查询,我需要在底部进行结果查询。

SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 1' AND SIDNAME LIKE 'Apple%';
SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 2' AND SIDNAME LIKE 'Apple%';

结果查询应该是: 苹果 Applesauces

2 个答案:

答案 0 :(得分:2)

使用__accepted_types

not exists()

或使用select o.sidname from securitygroupsid o where o.groupname = 'Group 1' and o.sidname like 'Apple%' and not exists ( select 1 from securitygroupsid i where i.groupname = 'Group 2' and i.sidname = o.sidname )

not in()

select o.sidname from securitygroupsid o where o.groupname = 'Group 1' and o.sidname like 'Apple%' and o.sidname not in ( select i.sidname from securitygroupsid i where i.groupname = 'Group 2' and i.sidname like 'Apple%' )

left join

答案 1 :(得分:1)

只需在查询之间添加except(SqlServer)即可。 (或MINUS for Oracle)

SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 1' AND SIDNAME LIKE 'Apple%';
EXCEPT
SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 2' AND SIDNAME LIKE 'Apple%';