5

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.

  • And if a parent row (at Table1) is not related to any child row (at Table2), it should be shown, correct? – ypercubeᵀᴹ Nov 3 '12 at 12:51
7

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
      ) 
  • ,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 '12 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, privacy policy and cookie policy

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