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 
2
  • Why don't you use EXISTS?? Commented Dec 25, 2014 at 11:56
  • how can i use exisist Commented Dec 25, 2014 at 18:40

2 Answers 2

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" 
Sign up to request clarification or add additional context in comments.

4 Comments

i have little modified my query
You can handle additonal filter criteria in the same way. Note there is a difference between placing the criteria in the inner LEFT JOIN criteria, and in the outer WHERE clause which you need to be wary of.
can you guide me about that
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.