基于另一个表中的值更新值

时间:2016-02-13 07:44:01

标签: sql oracle

Tables Involved我希望根据另一个表的列的值条件修改一个表上的列的值。

我正在使用代码:

UPDATE ORDERDETAIL
SET ORDERDETAIL.PRODUCTID = 'BASE1'
WHERE CUSTOMER.FIRSTNAME = 'JANE' AND CUSTOMER.LASTNAME = 'DOE';

这应该是非常简单的,我哪里出错?

2 个答案:

答案 0 :(得分:0)

您尚未明确指定第二个TABLE。加入应该工作。请记住始终在UPDATE

旁边表示别名而不是表名
UPDATE O_T
SET PRODUCTID = 'BASE1'
from ORDERDETAIL O_T
JOIN CUSTOMER C_T
ON O_T.SOME_COLUMN_NAME=C_T.SOME_COLUMN_NAME
WHERE C_T.FIRSTNAME = 'JANE' AND C_T.LASTNAME = 'DOE';

答案 1 :(得分:0)

如果您总是使用固定值,则使用exists查找与其他表中的条件匹配的记录:

UPDATE ORDERDETAIL OD
SET OD.PRODUCTID = 'BASE1'
WHERE EXISTS (
  SELECT NULL
  FROM CUSTOMER C
  JOIN ORDERS O ON O.CUSTOMERID = C.CUSTOMERID
  WHERE C.FIRSTNAME = 'JANE'
  AND C.LASTNAME = 'DOE'
  AND O.ORDERID = OD.ORDERID
);

或子查询:

UPDATE ORDERDETAIL OD
SET OD.PRODUCTID = 'BASE1'
WHERE OD.ORDERID IN (
  SELECT O.ORDERID
  FROM CUSTOMER C
  JOIN ORDERS O ON O.CUSTOMERID = C.CUSTOMERID
  WHERE C.FIRSTNAME = 'JANE'
  AND C.LASTNAME = 'DOE'
);

Oracle doesn't allow you直接在update语句中加入。如果您从另一个表中获取新值,则可以something like this