tags:

views:

103

answers:

4

Hi,

In a WHERE part of query we have

SELECT * FROM SomeTable st
WHERE 
NOT EXISTS 
  (SELECT 1 FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)
OR EXISTS 
  (SELECT 1 FROM Tab t2 WHERE (t2.A = st.A OR t2.B = st.A) AND t2.C IS NULL)

Seems like a good candidate for merging... But I'm staring on that for an hour without any idea.

Would you have some thoughts?

Thanks,

A: 

Try:

NOT EXISTS (SELECT 1 FROM Tab WHERE (Tab.A = @Id OR Tab.B = @ID)
            AND (Tab.C is null OR Tab.C != @Var))
Tony Andrews
Well in fact my @var = NULL ;-)And the second part is saying EXISTS (SELECT 1 FROM Tab WHERE (Tab.A = @Id OR Tab.B = @ID) AND Tab.C IS NULL)That is why I'm thinking about:SELECT 1 FROM spb_trade_match m3 WHERE NOT EXISTS(Tab.A = @Id AND Tab.C IS NOT NULL) OR (Tab.B = @Id AND Tab.C IS NOT NULL)
stic
No, in Oracle "Tab.C = NULL" is not TRUE when Tab.c IS NULL!!!
Tony Andrews
I think I caused some issues with my syntax. Sorry
stic
A: 

I think I've got it

SELECT * FROM SomeTable st
WHERE 
0 = (SELECT SUM (NVL(t1.C,0) FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)

What do you think? Of course that will work only for case where 'C' is expected to be NULL. If we are expecting some value, I think that the check

@SomeValue IN (SELECT t1.C FROM Tab t1 WHERE t1.A = st.A OR t1.B = st.A)

Will do?

stic
A: 

It looks as though you're trying to return all SomeTable values where there's no corresponding value on Tab where C is not null - in which case, the following should work:

SELECT * FROM SomeTable st
WHERE NOT EXISTS 
  (SELECT 1 FROM Tab t1 WHERE (t1.A = st.A OR t1.B = st.A) AND t2.C IS NOT NULL)

However, that's not exactly what your existing query does - in your query, if there are two corresponding records on Tab, where one record has a non-null value for C and the other is null, your query will return a corresponding row, but my query won't.

Mark Bannister
That is why I come up with the SUM approach on NVL (on the assumption that we can SUM C column), need to sort out the case when that is not possible. DECODE will be probably handy...
stic
So - do you know whether you can have null and non-null values of C in Tab for the same SomeTable record? Or is this an academic exercise?
Mark Bannister
+2  A: 
SELECT distinct st.* 
FROM SomeTable st 
     left outer join Tab t
     on st.a in (t.a,t.b)
WHERE t.c is null

Sometimes the simplest answer is to use a join rather than an exists.

Allan
@Allan: nice answer!
Bob Jarvis