简体   繁体   中英

How to update values of a column based on other table in Oracle SQL syntax

I have an emp table with these columns

emp_id  f_name      l_name      salary      dept_id
----------------------------------------------------
100     Steven      King        24000       90  
101     Neena       Kochhar     17000       50
102     Lex         De Haan     17000       90
103     Alexander   Hunold      9000        60

now I have t_emp table with these columns:

f_name      l_name      salary      dept_id
-------------------------------------------
Steven      King        24000       null 
Neena       Kochhar     17000       null
Lex         De Haan     17000       null
Alexander   Hunold      9000        null

Assume dept_id column was recently added here.

I want to update t_emp.dept_id column to be the same as emp.dept_id column. How could I do that?

When I try below insert into query, I get error msg :

Cannot insert NULL into ("GAURAV"."T_EMP"."LAST_NAME")

insert into t_emp(dept_id)
    select dept_id 
    from emp;

How could I do this single column update in t_emp table based on emp table?

Assuming the first and last names provide the match between the tables, then you can use a correlated subquery like this:

update t_emp te
    set dept_id = (select e.dept_id
                   from emp e
                   where e.f_name = te.f_name and e.l_name = te.l_name
                  );

You can add salary equivalence in as well, if that is important.

Note that actually storing the column is not important. You could fetch the information using a join :

select . . ., e.dept_id
from t_emp te join
     emp e
     on e.f_name = te.f_name and e.l_name = te.l_name;

It is usually better to save such information in one place and use join s to get the right info.

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