我在SQL
中有DB2
,并希望避免在第二个EXISTS
中重复UNION
子句中的条件,因为条件可能相当大。我怎么做?非常感谢任何帮助。
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')
答案 0 :(得分:1)
您为什么使用union
?这样做怎么样?
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')
)
)
答案 1 :(得分:1)
我认为这也可以通过@Override
public void setValueAt(Object aValue, int row, int column) {
if (DEF.get(column).getValueSetterFunction() != null) {
DEF.get(column).getObjectValueSetterFunction().accept(getObjectAt(row), aValue);
}
}
子句
where
答案 2 :(得分:0)
使用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)
;