【问题标题】:How to update values of a column based on other table in Oracle SQL syntax如何在 Oracle SQL 语法中根据其他表更新列的值
【发布时间】:2016-09-11 02:12:58
【问题描述】:

我有一个包含这些列的 emp

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

现在我有 t_emp 包含这些列的表:

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

假设最近在此处添加了 dept_id 列。

我想将t_emp.dept_id 列更新为与emp.dept_id 列相同。 我怎么能这样做?

当我尝试以下insert into 查询时,我收到错误消息:

无法将 NULL 插入 ("GAURAV"."T_EMP"."LAST_NAME")

insert into t_emp(dept_id)
    select dept_id 
    from emp;

如何根据emp 表在t_emp 表中进行单列更新?

【问题讨论】:

  • INSERT 创建新行。如果要更新现有行,请使用 UPDATE(或可能是 MERGE

标签: sql oracle


【解决方案1】:

假设名字和姓氏提供了表之间的匹配,那么您可以使用这样的相关子查询:

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
                  );

如果这很重要,您也可以添加 salary 等效项。

请注意,实际存储列并不重要。您可以使用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;

通常最好将此类信息保存在一个地方并使用joins 来获取正确的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多