2012-03-01 49 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语句看到。

相关问题