ORA-01427 UPDATE自加入ORACLE

时间:2016-10-25 09:24:50

标签: oracle

两个表,每个表都有employee_id和manager_id,链接到employee_id表有不同的employee_id。

UPDATE employee u
SET u.manager_id = (SELECT m.id
    FROM employee e
    JOIN old_db.employees oe ON e.last_name = oe.last_name
    JOIN old_db.employees om ON oe.manager_id = om.employee_id
    INNER JOIN employee m ON m.last_name = om.last_name
    WHERE e.id = u.id)
WHERE manager_id IS NULL;

给出

ERROR at line 2: ORA-01427: single-row subquery returns more than one row

我已尝试rownum=1,但这会使所有manager_id相同。

选择一个给定employee_id的查询会返回一个值

SQL> SELECT m.id
  2     FROM employee e
  3     JOIN old_db.employees oe ON e.last_name = oe.last_name
  4     JOIN old_db.employees om ON oe.manager_id = om.employee_id
  5     INNER JOIN employee m ON m.last_name = om.last_name
  6     WHERE e.id = 1805;

        ID
----------
      1804

1 个答案:

答案 0 :(得分:0)

问题的根本原因在表employees或表employee last_name中并不是唯一的。当你在姓氏上加入表格时,你会得到更多的一行。您可以使用下一个查询进行检查:

SELECT e.id, count(*), count(distinct m.id)
FROM employee e
JOIN old_db.employees oe ON e.last_name = oe.last_name
JOIN old_db.employees om ON oe.manager_id = om.employee_id
INNER JOIN employee m ON m.last_name = om.last_name
GROUP BY e.id; 

可能存在更合适的列加入它,例如employee_id,如果这样,您的查询可能会被重写为:

UPDATE employee u
SET u.manager_id = (SELECT oe.manager_id 
                    FROM old_db.employees oe
                   WHERE oe.employee_id = u.id)
WHERE manager_id IS NULL;