10

I've Table1 and Table2, Table1's PK is the FK of Table2. Now i need to perform a select from Table1 if and only if all the records in Table2 corresponding to a Table1 record has values (if any field value is null then skip).

ie, for an id in Table1 there have multiple sub ids in Table2. Out of those multiple ids if a particular field corresponds to any one id is null then select should be skipped.

Any one please help me out to write a single sql query for this requirement.

1
  • And if a parent row (at Table1) is not related to any child row (at Table2), it should be shown, correct? Nov 3, 2012 at 12:51

2 Answers 2

13

This is called an "anti-join" (or anti-semijoin). One way to write it in SQL is to use the NOT EXISTS construction:

SELECT t1.*
FROM Table1 AS t1
WHERE NOT EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
          AND t2.columnX IS NULL
      ) 

If - as your comment - you want a parent row (at Table1) not related to any child row (at Table2), to NOT be shown, add this (or join Table2 if you also want columns from the second table shown):

  AND EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
      ) 
1
  • ,Thanks...Also if a parent row (at Table1) is not related to any child row (at Table2), it should NOT be shown. The query is working for the other case. I used join along with your query to link both table1 and table2 and got the desired result.
    – Harun
    Nov 3, 2012 at 13:40
0
select t1.* from table1 t1
where exists(select 1 from table2 t2 where t2.FKcolumn = t1.PKcolumn 
             having count(*)=count(t2.columnX) and count(*)>0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.