tags:

views:

96

answers:

5

I've two tables where I like to select from the second table where it has a foreign key to first table.

The conditions are: (1). The qty field of second table must have a value greater than 0

Or

(2). First table record doesn't have a corresponding entry in the second table.

+1  A: 

I guess you need something like following

select * from the table1 t1
               where t1.value > 0 and 
                     t1.id not in (select distinct foreign_id  from table2 t2)
Salil
If table2.foreign_id can contain any NULL values you will need to exclude these from the NOT IN.
Martin Smith
A: 

Maybe this :

select * 
from table1 t1
where t1.qty > 0 
and not exists
(
    select * 
    from table2 t2 
    where t1.id = t2.id
)
Scorpi0
Condition 1 says that second table qty > 0
Bharat
+1  A: 

Maybe you want this?

select t1.pk, t2.qty
from   t1
left outer join t2 on t2.fk = t1.pk
where (t2.fk is null or t2.qty > 0);

"t2.fk is null" takes care of the t1 rows that have no matching t2 row, and "t2.qty > 0" takes care of the t1 rows that do have a matching t2 row.

Tony Andrews
Since this is Oracle, you can use t2.rowid IS NULL. I, personally, often assume that a FK is defined in the table and enforced with constraints... this is not always the case. ROWID is always available.
Rhose
A: 
A: 

If I understand the question correctly I think the following will give you the answer you want:

SELECT *
  FROM TABLE1 t1
  LEFT OUTER JOIN TABLE2 t2
    ON (t2.ID = t1.ID)
  WHERE t2.ID IS NULL OR
        t2.QTY > 0

Share and enjoy.

Bob Jarvis