我正在尝试更新表但我的问题是目标表有重复记录,因此我的更新因此失败。这是错误:尝试使用多个连接行中的值更新目标行。我知道在更新表时,我们必须加入唯一键但我不能从表中删除重复项,所以我正在寻找一个解决我的情况的方法。 CUSTOMERTABLE是具有重复项的那个。这是我的疑问:
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
FROM
(SELECT distinct(CUSTOMER_ID)AS ACCT_ID
,ED.CUSTOMER_NAME
, ED.CUSTOMER_ADDRESS
FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
WHERE ED.CUSTOMER_ID = TXN.CUS_ID
)AS X
WHERE X.ACCT_ID = CUSTOMERTABLE.ACCOUNT_NUMBER;
答案 0 :(得分:2)
尝试使用IN
子句编写它:
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
WHERE CUSTOMERTABLE.ACCOUNT_NUMBER IN
(SELECT CUSTOMER_ID
FROM CUSTOMER_RELATION ED
JOIN STG_CUSTOMER_REV TXN ON ED.CUSTOMER_ID = TXN.CUS_ID)
答案 1 :(得分:2)
这是另一个选项,如果IN
或CUSTOMER_RELATION
是大型表格,则与STG_CUSTOMER_REV
解决方案相比,可能会有更好的效果。
UPDATE C
SET SERVICE = 'BILLING'
FROM CUSTOMERTABLE C
WHERE EXISTS (SELECT 1
FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
WHERE ED.CUSTOMER_ID = TXN.CUS_ID AND CUSTOMER_ID = C.ACCOUNT_NUMBER);
答案 2 :(得分:0)
尝试对CustomerId进行分组
UPDATE CUSTOMERTABLE
SET SERVICE = 'BILLING'
FROM
(SELECT distinct(CUSTOMER_ID)AS ACCT_ID
,ED.CUSTOMER_NAME
, ED.CUSTOMER_ADDRESS
FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN
WHERE ED.CUSTOMER_ID = TXN.CUS_ID
GROUP BY ED.CUSTOMER_ID
)AS X
WHERE X.ACCT_ID = CUSTOMERTABLE.ACCOUNT_NUMBER;
您需要确保您的选择返回非重复。尝试使用没有update语句的select,并检查select是否包含你要删除的重复项。