0

我有两个表,它们有两个公共列“StationID”。

Create table t1(ID int, StationID bigint)
insert into t1 values
(0,1111),
(1,2222),
(2,34),
(3,456209),
(56,78979879),
(512,546)
go
Create table t2(StationID bigint, Descr varchar(50))
insert into t2 values
(-1,'test-1'),
(0,'test0'),
(1,'test1'),
(2,'test2'),
(5001,'dummy'),
(5002,'dummy'),
(6001,'dummy')
go

现在我们注意到并非每个 t1.StationID 都在 t2.StationID 中。运行脚本就可以证明了。

select distinct StationID from t1 as A
where not exists
(select * from t2 as B where B.StationID =A.StationID)

结果是:

StationID
34
546
1111
2222
456209
78979879

现在我想用上面丢失的 StationID 填充 t2,列 Descr 可以是任何虚拟数据。我的真实案例有上千条记录,如何使用脚本来实现呢?

4

2 回答 2

4
insert into t2 (StationID, Descr)
select distinct StationID, 'dummy' 
from t1 as A
where not exists
   (select * from t2 as B where B.StationID =A.StationID)
于 2013-03-11T13:49:38.207 回答
2
INSERT INTO 
    t2 
SELECT DISTINCT 
    stationid, 'dummy'  
FROM 
    t1 
WHERE 
    stationid NOT IN (SELECT stationid FROM t2)

(作为其他人的替代品)。

于 2013-03-11T13:51:54.943 回答