相关更新查询

时间:2016-04-07 05:37:52

标签: oracle correlated-subquery

我无法获得以下oracle相关查询来仅对记录的子部分执行更新。目前它更新所有记录。

我有一张表(TBL_REQUESTS),看起来像:

request_id    employee_id    status
------------------------------------
1              1000
1              1001
2              1003
2              1004
2              1005
3              1006

我有一个看起来像的视图(VW_STATUS):

employee_id   status
---------------------
1000           failed
1001           closed
1002           open
1003           open
1004           close
1005           open
1006           open

我正在尝试编写一个UPDATE语句,该语句将更新TBL_REQUESTS中员工的状态字段及其对应的状态,其中来自VW_STATUS,其中TBL_REQUESTS.request_id等于传递的值。额外的皱纹是VW_STATUS中每位员工可能有超过1条记录,但是如果这会产生问题,我总是可以在VIEW中寻找解决方法。

此尝试更新了TBL_REQUESTS中的每一行:

UPDATE TBL_REQUESTS r1
SET r1.status =
  (SELECT s.status
   FROM VW_STATUS s
   INNER JOIN TBL_REQUESTS r2 ON s.employee_id = r2.employee_id
   WHERE rd2.request_id = 2)
WHERE EXISTS
    (SELECT s.status
     FROM VW_STATUS s
     INNER JOIN TBL_REQUESTS r2 ON s.employee_id = r2.employee_id
     WHERE rd2.request_id = 2)

1 个答案:

答案 0 :(得分:1)

我认为编写此查询的更好方法可能就是这个 -

UPDATE TBL_REQUESTS r1
SET r1.status =
  (SELECT s.status
   FROM VW_STATUS s
   INNER JOIN TBL_REQUESTS r2 ON s.employee_id = r2.employee_id
   WHERE rd2.request_id = 2)
WHERE r1.employee_id in 
    (SELECT s.employee_id
     FROM VW_STATUS s
     INNER JOIN TBL_REQUESTS r2 ON s.employee_id = r2.employee_id
     WHERE rd2.request_id = 2)

这应该限制查询仅在具有request_id = 2的employee_ids上运行。