Sql 如何避免联合体中EXISTS子句中的条件重复

Sql 如何避免联合体中EXISTS子句中的条件重复,sql,db2,Sql,Db2,我在DB2中有这个SQL,我希望避免重复第二个UNION中EXISTS子句中的条件,因为条件可能相当大。我该怎么做?非常感谢您的帮助 select id from table t where t.given_name = 'good' and t.time = 1 and exists (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK') union select id from table t where t

我在
DB2
中有这个
SQL
,我希望避免重复第二个
UNION
EXISTS
子句中的条件,因为条件可能相当大。我该怎么做?非常感谢您的帮助

select id from table t where t.given_name = 'good' and t.time = 1 and exists
    (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK') union
select id from table t where t.given_name = 'good' and t.time = 2 and not exists
    (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK') 

您为什么要使用
联合
?这么做怎么样

select id
from table t
where t.given_name = 'good' and
      t.time in (1, 2) and
      exists (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK');
如果
id
可能有重复项,请在外部查询中使用
select distinct

编辑:

我想我误解了最初的疑问。逻辑是:

select id
from table t
where t.given_name = 'good' and
      ( (t.time = 1 and exists (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK')
        ) or
        (t.time = 2 and not exists (select 1 from table t1 where t1.id = t.id and t1.surname = 'OK')
        )
       )

我认为这也可以通过
where
子句来实现

where given_name = 'good' and 
     (times = 1 and surname = 'OK') or 
     (times = 2 and surname <> 'OK')
其中给定的名称='good'和
(时报=1,姓氏=OK)或
(次数=2,姓氏“OK”)

使用WITH子句删除冗余

with t2 as (select * from t1 where surname = 'OK')
select id from table t where t.given_name = 'good' and t.time = 1 and exists
    (select 1 from table t2 where t2.id = t.id) union
select id from table t where t.given_name = 'good' and t.time = 2 and not exists
    (select 1 from table t2 where t2.id = t.id) 
;
如果需要的话,你也可以对另一张桌子做同样的事情

with t2 as (select * from t1 where surname = 'OK')
,    tt as (select * from t  where given_name = 'good')
select id from table tt where tt.time = 1 and exists
    (select 1 from table t2 where t2.id = tt.id) union
select id from table tt where tt.time = 2 and not exists
    (select 1 from table t2 where t2.id = tt.id) 
;

感谢您的输入Gordon。我使用union是因为我想要的ID是两个独立的组ID,一个组满足存在条件,另一个组满足不存在条件。第一个选择按t.time-1过滤,第二个选择按t.time=2过滤。
姓氏应参考外部查询。非常感谢P.Vernon。我在发布问题后发现了With子句。这就是我想要摆脱冗余的原因。干杯,罗奇