简体   繁体   中英

Outer join giving same results as inner join if using where clause

The following SQL statement:

select * from employees e   
left join departments d on e.deptid = d.deptid   
where ( d.deptname = 'HR' or d.deptname  = 'HR & Accounts')    

Produces the same results as the following inner join:

select * from employees e  
   inner join departments d on e.deptid = d.deptid and d.deptname like '%HR%';  

In what way they produce the same result.

I mean is the first query equivalent eg of:

  1. Select * from employees and filter using where
  2. Do left join?

What are the steps of the first query that make it the same as the inner join?

For rows that don't match the condition of the Outer Join, the value of any column in the joined table is NULL. The Where clause happens (conceptually) after the Joins are processed, so any condition testing those columns will be false (or, strictly speaking, NULL).

If you want to include all rows from one table, but only match rows in a second table which meet a condition, you have to add that condition to the ON clause of your Outer Join.

Also, note that because an Inner Join discards rows where there is no match, a condition in the ON clause of an Inner Join has the same effect as if it was in the Where clause.

With your second query, you filter in the join condition.

The first query left joins employees to departments using deptid. It returns all possible results to then filter using your where clause. This filtering after essentially alters the query to return results similar to an inner join query.

You could alter the first query to show you what it fails to return because of your where clause like this:

select *, CASE WHEN d.deptname = 'HR' or d.deptname  = 'HR & Accounts' THEN 1 ELSE 0 END as HR
from employees e 
left join departments d on e.deptid = d.deptid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM