我有两个表,它们有两个公共列'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可以是任何虚拟数据。 我的真实案例有数千条记录,如何使用脚本来实现它?
答案 0 :(得分: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)
答案 1 :(得分:2)
INSERT INTO
t2
SELECT DISTINCT
stationid, 'dummy'
FROM
t1
WHERE
stationid NOT IN (SELECT stationid FROM t2)
(作为其他人的替代方案)。