使用Inner Join更新抛出SQL命令未正确结束错误

时间:2018-01-27 11:19:23

标签: sql oracle oracle11g

我有两张桌子。

部门(表)

DEPTID NUMBER(38)
NAME CHAR(20)
RANK NUMBER(38)

员工(表)

EMPID NUMBER(38)
DEPTID NUMBER(38)
NAME CHAR(40)
AGE NUMBER(38)
SALARY NUMBER(38)

我正在尝试运行以下查询,这会不断抛出错误。 查询是根据每个部门员工的平均年龄更新部门表中的排名。

UPDATE d 
SET d.rank = T.rank 
FROM  department d
INNER JOIN 
     (SELECT
          rownum as rank, age, deptId 
      FROM 
          (SELECT 
               AVG(age) AS age, deptid 
           FROM employee
           GROUP by deptId
           ORDER BY age DESC)) AS T ON T.deptId = d.deptId;

1 个答案:

答案 0 :(得分:2)

Oracle中UPDATE语句的语法不支持连接。

MERGE语句可用于执行此任务:

MERGE INTO DEPARTMENT d
USING (
     SELECT
             rownum as rank, age, deptId 
     FROM 
       (SELECT AVG(age) AS age, deptid 
        FROM employee
        GROUP by deptId
        ORDER BY age DESC)
) q
ON ( d.DEPTID = q.DEPTID )
WHEN MATCHED THEN UPDATE
SET d.RANK = q.rank

工作演示:http://sqlfiddle.com/#!4/f0f34/2