2012-03-01 53 views
0

表一更新表,但唯一的非重複記錄

name, street, city, state, zip 
bill, 123 main, newcity, null, 77777 
bill, 123 main, newcity, null, 77777 
fred, 23 west, greattown, null, 12345 
bob, 4 a St, nowhere, null, 34567 

表B中

name, street, city, st, zip 
bill, 123 main, newcity, me, 77777 
bill, 123 main, newcity, me, 77777 
fred, 23 west, greattown, ny, 12345 
bob, 4 a St, nowhere, wy, 34567 

我想要做的

update table A 
set state = tB.st 
from 
table A tA inner join table B tB 
on (tA.name = tB.name and tA.street = tB.street) 

,但我不想更新2條記錄「法案,123主要,newcity,null,77777「。

如何從表中排除這些行?

感謝 查爾斯

+2

什麼是你的DBMS? SQL Server或Oracle或MySQL? – 2012-03-01 22:05:27

+0

表A上是否有一些使重複記錄不同的id字段? – 2012-03-01 22:08:01

+0

您可以在UPDATE語句結尾處的「AND NOT EXISTS(SELECT name FROM A WHERE name = tB.name)」一行中找到。 – 2012-03-01 22:15:36

回答

1

在SQL Server 2005 +,你可以做這樣的事情:

; 
WITH A_counted AS (
    SELECT 
    *, 
    cnt = COUNT(*) OVER (PARTITION BY name, street, city, zip) 
    FROM TableA 
), B_counted AS (
    SELECT 
    *, 
    cnt = COUNT(*) OVER (PARTITION BY name, street, city, zip) 
    FROM TableB 
) 
UPDATE A_counted 
SET state = B.state 
FROM B_counted B 
WHERE A_counted.name = B.name, 
    AND A_counted.street = B.street, 
    AND A_counted.city = B.city, 
    AND A_counted.zip = B.zip 
    AND A_counted.cnt = 1 
    AND B.cnt   = 1 
+0

這個爲我工作,謝謝 – Charles 2012-03-02 16:42:47

0

我看到它的方式是:

1)在A中出現多次的記錄中創建一個臨時表。

2)創建B中的所有記錄的是不要在臨時表從步驟1

3匹配記錄的第二臨時表)從步驟更新所有記錄2.

0

你應該只需要在您的加入中附加1個附加條件:

update table A 
set state = tB.st 
from 
table A tA inner join table B tB 
on (tA.name = tB.name and tA.street = tB.street and tA.name <> 'Bill') 

這應該排除這兩行,甚至不會被update語句看到。

相關問題