1

这很简单,我想更新一个表,但前提是满足另一个表中的条件。我目前的查询:

UPDATE Table1
SET Table1.value='1234'
WHERE   ID IN 
(   
  (A sub query returning all the id's needed) 
)

这种工作,但它更新到许多值。问题是还有第二个条件,即:

AND Table2.value = 'Pudding'

但是看到它是一个不同的表它不起作用。而且我不知道如何在 Oracle 中加入它。看过其他一些帖子,但它们似乎与我的具体问题无关。尝试使用我也在子查询中使用的连接添加 From 子句,但我无法在此处找到将其放入 oracle 中的更新语句中。

编辑:示例数据库

表格1

ID    Key1     Key2     Value
1    A1       B1       345
2    A1       B2       75
3    A2       B1       45 

表2

Key1     Key2     Value
A1       B1       'Pudding'
A1       B2       'Pudding'
A2       B1       'Something else' 

是的,Table2 也是子查询的一部分,但其他大约 6 个表也是如此。我相信列出子查询的整个结构只会更加令人困惑,因为它会带回一系列已经正常工作的 ID。

但结果是示例中的前两行需要更新。

4

1 回答 1

1

您可以尝试像这样将存在与子查询一起使用,因为表中有两列需要比较。

UPDATE Table1 t1
SET t1.Value = '1234'
WHERE t1.ID IN 
    (   
      --(A sub query returning all the id's needed) 
    ) 
and 
    exists (
     select 1 
     from Table2 t2
     where t1.Key2 =t2.Key2 and t1.Key1 =t2.Key1 and t2.Value = 'Pudding'
    )

这是一个示例

CREATE TABLE Table1(
  ID INT,
  Key1 VARCHAR(50),
  Key2 VARCHAR(50),
  Value VARCHAR(50)
);

INSERT INTO Table1 VALUES (1,'A1','B1','345');
INSERT INTO Table1 VALUES (2,'A1','B2','75');
INSERT INTO Table1 VALUES (3,'A2','B1','45');

CREATE TABLE Table2(
  Key1 VARCHAR(50),
  Key2 VARCHAR(50),
  Value VARCHAR(50)
);

INSERT INTO Table2 VALUES ('A1','B1','Pudding'); 
INSERT INTO Table2 VALUES ('A1','B2','Pudding'); 
INSERT INTO Table2 VALUES ('A2','B1','Something else'); 

UPDATE Table1 t1
SET t1.Value = '1234'
WHERE  exists (
 select 1 
 from Table2 t2
 where t1.Key2 =t2.Key2 and t1.Key1 =t2.Key1 and t2.Value = 'Pudding'
)

查询 1

select * from Table1

结果

| ID | KEY1 | KEY2 | VALUE |
|----|------|------|-------|
|  1 |   A1 |   B1 |  1234 |
|  2 |   A1 |   B2 |  1234 |
|  3 |   A2 |   B1 |    45 |
于 2018-08-31T11:18:00.860 回答