Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better way of writing this query?

Tags:

sql

I have a simple join query as follows.

select * 
from user u left join 
     user_roles ur 
     on  ur.user_id = u.user_id 
     and ur.created_by = 'Mike'
where u.division = 'some division'

OR

select * 
from user u left join 
     user_roles ur 
     on  ur.user_id = u.user_id 
where u.division = 'some division' 
and   ur.created_by = 'Mike'

The point is here is I have moved the additional filter clause condition from left join to where clause.

Does it make any difference if I join two tables on more than column or put it in where clause?

like image 374
ashishjmeshram Avatar asked Dec 26 '22 18:12

ashishjmeshram


1 Answers

Yes it makes a big difference.

You are basicalling nullifying the left join and making it an inner join, hiding user roles not created by Mike

Bell Mike
Toe Mike
Bob Jerry

first query returns

Bell Mike
Toe Mike
Bob NULL

second Query returns

Bell Mike
Toe Mike
like image 61
jenson-button-event Avatar answered Jan 15 '23 10:01

jenson-button-event