我有一个表结构,例如,
表T1,
10 - A1 - A11 - AV1 - 1 - 0 - 0
20 - A2 - A22 - AV2 - 1 - 0 - 0
30 - A3 - A33 - AV3 - 1 - 0 - 0
40 - A4 - A44 - AV4 - 1 - 0 - 0
50 - A5 - A55 - AV5 - 1 - 0 - 0
60 - A4 - A66 - AV6 - 1 - 0 - 0
表T2,
10 - A1 - A11 - AV1 - 10 - 20 - 30
20 - A2 - A22 - AV2 - 100 - 200 - 300
30 - A3 - A33 - AV3 - 11 - 22 - 33
40 - A4 - A44 - AV4 - 1 - 2 - 3
现在,我想编写一个更新查询,通过检查
来更新表T1中的PDX1,PDEX2,PDEX3列的表T1的PREX1,PREX2,PREX3列。
(ID,PART,PRCODE)在T1和T2中匹配(公共)记录。
如果更新很好,那么我想得到如下的表T1,
表T1,
10 - A1 - A11 - AV1 - 10 - 20 - 30
20 - A2 - A22 - AV2 - 100 - 200 - 300
30 - A3 - A33 - AV3 - 11 - 22 - 33
40 - A4 - A44 - AV4 - 1 - 2 - 3
50 - A5 - A55 - AV5 - 1 - 0 - 0
60 - A4 - A66 - AV6 - 1 - 0 - 0
尝试了以下查询,但没有按预期工作。
update T1 a
inner join T2 b on (
(a.ID=b.ID) AND (a.PART=b.PART) (a.PRCODE=b.PRCODE)
)
)
set a.PREX1= b.PDEX1,
a.PREX2 = b.PDEX2,
a.PREX3 = b.PDEX3
where ( (a.ID=b.ID) AND (a.PART=b.PART) (a.PRCODE=b.PRCODE) )
Error message: Keyword Inner not expected. valid tokens SET.
还尝试通过以下查询更新单个列,
update T1
set T1.PREX1 = (select T2.PDEX1
FROM T2, T1
( (T1.ID=T2.ID) AND
(T1.PART =T2.PART) AND
(T1.PRCODE=T2.PRCODE)
) where T1.ID=10;
错误结果:此查询将所有PREX1列记录更新为相同的值,这是不期望的。
如果我错过了任何条件,请告诉我。
提前致谢!
答案 0 :(得分:1)
更好的方法是使用merge statement
MERGE INTO T1
USING T2
ON T1.ID = T2.ID and T1.PART = T2.PART and T1.PRCODE = T2.PRCODE
WHEN MATCHED THEN UPDATE SET T1.PREX1=T2.PDEX1,
T1.PREX2=T2.PDEX2,
T1.PREX3=T2.PDEX3;
或者使用可以使用子查询进行更新
Update T1
Set PREX1 =(Select MAX(PDEX1)
from T2
Where T1.ID = T2.ID
and T1.PART = T2.PART
and T1.PRCODE = T2.PRCODE
),
PREX2 =(Select MAX(PDEX2)
from T2
Where T1.ID = T2.ID
and T1.PART = T2.PART
and T1.PRCODE = T2.PRCODE
),
PREX3 =(Select MAX(PDEX3)
from T2
Where T1.ID = T2.ID
and T1.PART = T2.PART
and T1.PRCODE = T2.PRCODE
);
答案 1 :(得分:0)
您应该可以运行:
Update T1
Set PREX1 =
(Select PDEX1
from T2
Where T1.ID = T2.ID
and T1.PART = T2.PART
and T1.PRCODE = T2.PRCODE
);