简体   繁体   English

从另一个表更新表

[英]Update a table from another table

I want to update a field based on another table field. 我想基于另一个表字段更新字段。 The table is like this: 表格是这样的:

TABLE A
SID  SMONTH  STID VID  VVID
1    201312   s10  v5    ?
2    201312   s10  v5    ?
1    201312   s11  v7    ?
2    201401   s11  v7    ?
1    201312    s1  v9    ?
2    201401    s1  v9    ?
1    201312    s1  v60   ?
1    201312    s1  v71   ?

In the above table A , i need to update VVID column with the VVID from the below table B. 在上表A中,我需要使用下表B中的VVID更新VVID列。

TABLE B
VVID   STID  VID   WEIGHT
v1     s10   v5    0.5
v2     s10   v5    7.5
v1     s11   v7    1.5
v2     s11   v7    6.5
v1     s1    v9    5
v2     s1    v9    5
v1     s1    v60   5
v1     s1    v71   5

In the above table B , VVID is generated based on three fields STID , VID and WEIGHT . 在上表B中,基于三个字段STID,VID和WEIGHT生成VVID。 But in the table A , i dont have WEIGHT field. 但在表A中,我没有WEIGHT字段。 So if i use the below code i am getting "single row query returns more than one row" error. 所以如果我使用下面的代码我得到“单行查询返回多行”错误。

UPDATE  A
SET VVID = (SELECT distinct VVID
          FROM  B
          WHERE B.STID = A.STID and B.VID = A.VID  ) 

Please give me suggestions. 请给我一些建议。

Thanks Sathish 谢谢Sathish

Here your inner query is returning more than one row as the additional criteria for comparing the weight is missing so for example STID = s10 and VID = v5 the inner query will return two rows with VVID = v1 and VVID = v2. 这里你的内部查询返回多行,因为缺少比较权重的附加条件,例如STID = s10和VID = v5,内部查询将返回两行,其中VVID = v1,VVID = v2。 The update clause requires a single value after SET. update子句在SET之后需要一个值。

You can modify your query to update the max or min of VVID if it is acceptable for your application 如果您的应用程序可以接受,您可以修改查询以更新VVID的最大值或最小值

UPDATE A SET VVID = (SELECT MIN(VVID) FROM B WHERE B.STID = A.STID and B.VID = A.VID) 更新SET VVID =(从B中选择MIN(VVID)B.STID = A.STID和B.VID = A.VID)

or 要么

UPDATE A SET VVID = (SELECT MAX(VVID) FROM B WHERE B.STID = A.STID and B.VID = A.VID) 更新SET VVID =(从B中选择MAX(VVID),其中B.STID = A.STID和B.VID = A.VID)

I think you can update with an INNER JOIN query 我认为您可以使用INNER JOIN查询进行更新

UPDATE A 
JOIN B
ON  B.STID = A.STID 
AND B.VID = A.VID 
SET A.VVID = B.VVID

Please use union with constant value instead of join. 请使用具有常数值的联合而不是联接。 For details please refer to the post http://scn.sap.com/docs/DOC-40619 有关详细信息,请参阅http://scn.sap.com/docs/DOC-40619

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM