0

对,我有以下数据需要插入到名为 locals 的表中,但我只想在 locals 表中不存在街道字段时插入它。数据和字段如下:

Street    PC       Locality
------------------------------
Street1   ABC xyz  A
Street2   DEF xyz  B

依此类推,但如果 Street 字段尚未出现在 locals 表中,我想插入到 Locals 表中。

我正在考虑使用以下内容:

INSERT
  INTO Locals (Street,PC,Locality) 
       (
            SELECT DISTINCT s.Street
              FROM Locals_bk s
             WHERE NOT EXISTS (
                      SELECT 1
                        FROM Locals l
                       WHERE s.Street = l.Street
                   )
       )
     ;

但我意识到这只会插入街道字段而不是同一行的其余数据。

4

4 回答 4

3
insert into Locals (Street, PC, Locality) 
select b.Street, b.PC, b.Locality
from Locals_bk as b
where not exists (select * from Locals as t where t.street = b.street)

或者

insert into Locals (Street, PC, Locality) 
select b.Street, b.PC, b.Locality
from Locals_bk as b
where b.street not in (select t.street from Locals as t)
于 2013-08-16T11:09:49.087 回答
1

怎么样

INSERT [Locals]
SELECT
            [Street],
            [PC],
            [Locality]
    FROM
            [Locals_bk] bk
    WHERE
         NOT EXIST (
             SELECT * FROM [Locals] l WHERE l.[Street] = bk.[Street]
         );
于 2013-08-16T11:12:39.653 回答
1

您可以使用 NOT IN :

    INSERT into Locals (Street,PC,Locality) 
    SELECT s.Street, s.PC, s.Locality
    FROM Locals_bk as s
    WHERE NOT IN (SELECT * FROM Locals as t WHERE t.street = s.street)
于 2013-08-16T11:15:50.633 回答
0

以下从与街道匹配的任意行中获取所需的字段:

insert into Locals (Street, PC, Locality) 
select s.Street, s.PC, s.Locality
from (select s.*, row_number() over (partition by s.Street order by (select NULL)) as seqnum
      from Locals_bk s
     ) s
where seqnum = 1 and
     NOT EXISTS (SELECT 1
                  FROM Locals l
                  WHERE s.Street = l.Street);

如果您知道这些值始终相同,则可以这样做:

insert into Locals (Street, PC, Locality) 
select distinct s.Street, s.PC, s.Locality
from Locals_bk s
where NOT EXISTS (SELECT 1
                  FROM Locals l
                  WHERE s.Street = l.Street);
于 2013-08-16T11:11:17.440 回答