2

How can I write following query using left join here is my Sample Query

SELECT * 
FROM STUDENT st 
WHERE st.stdid not IN 
   (    SELECT csch.stid 
        FROM courseSchedule csch,    section sctn 
        WHERE cschno.sectno = sctn.sectno 
             AND cschno.college= sctn.college
             AND sctn.college = st.college AND sctn.year = 2013 and sctn.semester = 'spring' 
     )
     AND st.college = 1
Khurram Ali
  • 1,659
  • 4
  • 20
  • 37
Waqas Ali
  • 41
  • 5

2 Answers2

5

TO move the NOT IN subquery to a LEFT JOIN, do left join on the NOT IN key criteria, and instead, check for the Right table KEY as NULL. Note that you can also convert the WHERE join in the subquery to an ANSI join as well:

SELECT st.*
  FROM STUDENT st 
    LEFT JOIN courseSchedule csch 
      ON st.stdid = csch.stid 
    INNER JOIN section sctn 
      ON cschno.sectno = sctn.sectno 
     AND cschno.college= sctn.college
     AND sctn.college = st.college 
     AND sctn.year = 2013 
     AND sctn.semester = 'spring'
  WHERE st.college = 1
     AND csch.stid IS NULL; -- "Not IN"
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • i have little modified my query – Waqas Ali Dec 25 '14 at 10:10
  • 2
    You can handle additonal filter criteria in the same way. Note [there is a difference](http://stackoverflow.com/a/10297312/314291) between placing the criteria in the inner `LEFT JOIN` criteria, and in the outer `WHERE` clause which you need to be wary of. – StuartLC Dec 25 '14 at 10:12
  • can you guide me about that – Waqas Ali Dec 25 '14 at 18:33
  • I've added the additional criteria. Basically, unless ALL the criteria are met, the `RHS` table columns will be NULL because of the Left join, which is detected in the `WHERE` clause. – StuartLC Dec 26 '14 at 20:07
1

@Waqas, I would use EXISTS for this (actually NOT EXISTS) as a commenter suggested above:

SELECT * FROM STUDENT st
 WHERE st.college = 1
   AND NOT EXISTS ( SELECT 1 FROM courseSchedule csch, section sctn
                     WHERE csch.stid = st.stdid
                       AND csch.sectno = sctn.sectno
                       AND csch.college = sctn.college
                       AND sctn.year = 2013
                       AND sctn.semester = 'spring'
                       AND sctn.college = st.college )

I notice you also have a typo in your query (the alias for courseSchedule is csch, not cschno).

Hope this helps.

David Faber
  • 12,277
  • 2
  • 29
  • 40