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

来自同一表的两个SQL查询之间的差异,sql,Sql,表SECURITYGROUPSID: GROUPNAME | SIDNAME -------------------------- Group 1 Apple Group 1 Apples Group 1 Applesauce Group 1 Applesauces Group 1 Appleton Group 2 Apple Group 2

表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值的差异。例如,如果我执行以下两个查询,我需要底部的结果查询

SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 1' AND SIDNAME LIKE 'Apple%';
SELECT SIDNAME FROM SECURITYGROUPSID WHERE GROUPNAME = 'Group 2' AND SIDNAME LIKE 'Apple%';
查询结果应为: 苹果 使用
的苹果酱不存在()

或者使用
不在()

左连接

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%'
      )
select o.sidname 
from securitygroupsid o
  left join securitygroupsid i
    on o.sidname = i.sidname
   and o.groupname = 'Group 1'
   and i.groupname = 'Group 2'
where o.sidname like 'Apple%'
  and i.sidname is null

只需在查询之间添加一个除
(SqlServer)之外的
。(或Oracle的


您使用的是哪种数据库管理系统?博士后?Oracle?对于给定的示例,这也是一个很好的答案。请注意,
except
将消除重复结果(排序操作会有一些开销),因为我的答案中的选项不会。SQL Server没有实现
,除了所有的
,这将避免重复数据消除和额外的排序成本。也就是说,将返回一个集合。
select o.sidname 
from securitygroupsid o
  left join securitygroupsid i
    on o.sidname = i.sidname
   and o.groupname = 'Group 1'
   and i.groupname = 'Group 2'
where o.sidname like 'Apple%'
  and i.sidname is null
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%';