使用联接SQL Oracle更新表

时间:2019-01-01 14:01:59

标签: sql oracle join

我需要更新一个表的几列,但是一条信息存储在另一个表中,所以我假设我需要加入它们,但是我不确定该怎么做。基本上,我需要更新姓氏为Parker的工作人员的职位(办公室是T06)和开始日期(原始开始日期为'05 -FEB-09,08:00')

到目前为止,我有:

UPDATE JOB
SET JOB_TITLE = 'Head of Technology'
WHERE OFFICE = 'T06' 
AND SET START_DATE = '26-JUN-17, 08:00'
WHERE START_DATE = '05-FEB-09, 08:00'
FROM JOB
JOIN STAFF
ON JOB.STAFF_ID = STAFF.STAFF_ID
WHERE STAFF.LAST_NAME = 'Parker';

3 个答案:

答案 0 :(得分:1)

正确的语法为

update job
set job_title = 'Head of Technology',
    start_date = '26-JUN-17, 08:00'
where office = 'T06'
      and start_date = '05-FEB-09, 08:00'
      and staff_id =(select staff_id
                     from staff
                     where last_name = 'Parker'
                    );

但是,可能需要对其进行修改(START_DATE条件很奇怪)。

此外,还不清楚START_DATE数据类型是什么。 应该DATE,但是您的代码建议使用字符串(VARCHAR2)。


备用#1(注意TO_DATE)功能:

update job
set job_title = 'Head of Technology',
    start_date = to_date('26-JUN-17, 08:00', 'dd-mon-yy, hh24:mi')
where office = 'T06'
      and start_date = to_date('05-FEB-09, 08:00', 'dd-mon-yy, hh24:mi')
      and staff_id =(select staff_id
                     from staff
                     where last_name = 'Parker'
                    );

备用#2(请注意CASE子句中的START_DATEWHERE的注释):

update job
set job_title = 'Head of Technology',
    start_date = case when start_date = to_date('05-FEB-09, 08:00', 'dd-mon-yy, hh24:mi')
                           then         to_date('26-JUN-17, 08:00', 'dd-mon-yy, hh24:mi')
                      else start_date
                 end
where office = 'T06'
      and staff_id =(select staff_id
                     from staff
                     where last_name = 'Parker'
                    );

答案 1 :(得分:0)

我会使用EXISTS

UPDATE JOB
    SET JOB_TITLE = 'Head of Technology'
        OFFICE = 'T06',
        START_DATE = '26-JUN-17, 08:00'
WHERE START_DATE = '05-FEB-09, 08:00' AND
      OFFICE = 'T06' AND
      EXISTS (SELECT 1
              FROM STAFF
              WHERE JOB.STAFF_ID = STAFF.STAFF_ID AND
                    STAFF.LAST_NAME = 'Parker' 
             );

答案 2 :(得分:0)

最原生的方法是使用updatable join view

简单地使您联接并选择所有相关列,然后添加UPDATE来修改联接。

update (
 select job.*
 FROM JOB
 JOIN STAFF
 ON JOB.STAFF_ID = STAFF.STAFF_ID
 WHERE STAFF.LAST_NAME = 'Parker')
set JOB_TITLE = 'Head of Technology',
START_DATE = '26-JUN-17, 08:00'

唯一的要求是,STAFF_ID表中的列STAFF必须具有唯一索引(例如主键)。

否则,您会收到错误ORA-01779: cannot modify a column which maps to a non key-preserved table

如果您需要使用联接表中的值(而不是大小写)进行更新,则UPDATE的这种方式非常有用。