简体   繁体   中英

using an inner or left join in an update?

Though my sql knowledge is pretty good, I cannot get my head around the difference in a left vs inner join specifically when doing an update .

employee_table
column1:id
column2:socialsecurity


private_info_table
column1:id
column2:socialsecurity

I need to update employee_table.socialsecurity to be private_info_table.socialsecurity

should I do a left or inner join: ???

update e
set e.socialsecurity=p.socialsecurity
from employee_table e
join private_info_table p  --should this be left or inner join?
on p.id=e.id

Left Join

Select *
from A 
left join B on a.id = b.pid

In the conditions a.id = b.pid , every row is returned for both A and B BUT if the value from A (ieaid) doesn't match the value from B (ie, B), all fields of B will be null. On the other hand, for those rows where this condition is true, all values for B are shown. Notice that A's values have to be returned because it is on the left of the 'left' keyword.

Inner Join

Select *
from A 
inner join B on a.id = b.pid

Rows are returned for rows where a.id = b.pid is true, otherwise no rows are returned if it is false. This is a mutually exclusive join.

In your case, don't use a left join because all records on the left of the 'left' keyword will be updated with null or non-null values. This means you will unintentionally update non-matched record with null values based upon my description of left joins.

It should be an inner join if you just want to update those records that are in both tables. If you do a left join it will update the employee table to be null wherever the id isn't found in the private info table.

The reason this matter is if you have some social security numbers in the employee table that already that aren't found in the private info table. You wouldn't want to erase them with a null value.

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