将数据从一个表迁移到另一个表

时间:2019-08-11 13:09:13

标签: sql sql-insert

我有两个表,我必须将数据从一个转移到另一个。

表1:员工

home_address string

表2 emp_address

address      string 
emp_id       int 
is_permanent bool

我需要将数据从一个迁移到另一个。

所以插入时我只有2个条件:

  1. 我无法将该雇员的地址插入已经插入的 emp_address 中。

  2. 如果没有为员工插入地址,即 is_permanent 标志设置为true(即,如果没有为员工设置单个条目,则为是,否则是假)

我似乎无法理解该怎么做。

3 个答案:

答案 0 :(得分:2)

使用not exists

insert into emp_address (address,emp_id,is_permanent)
    select ea.address, e.id, IIF(ea.number IS NOT NULL,0,1)  
      from employees e
      left join dbo.emp_address ea 
        on e.id=ea.emp_id 
     where not exists ( select 0 
                           from dbo.emp_address 
                           where e.id = emp_id 
                             and e.home_address = address )
       and ea.address is not null

答案 1 :(得分:2)

如果要插入带有适当的is_permanent标志的新地址,则可以两次使用not exists

insert into emp_address (address, emp_id, is_permanent)
    select e.address, e.id,
           (case when not exists (select 1
                                  from dbo.emp_address ea
                                  where ea.emp_id = a.id and
                                        ea.address = e.home_address and
                                        ea.is_permanent = 1
                                 )
                 then 1 else 0
             end)    
    from employees e 
    where not exists (select 1
                      from dbo.emp_address ea
                      where e.id = ea.emp_id and  e.home_address <> ea.address
                     )

答案 2 :(得分:2)

在WHERE子句和CASE语句中使用NOT EXISTS来确定要在列insert into emp_address (address, emp_id, is_permanent) select e.address, e.id, case when exists ( select 1 from emp_address ea where e.id = ea.emp_id and ea.is_permanent = 1 ) then 0 else 1 end from employees e where e.home_address is not null and not exists ( select 1 from emp_address ea where e.id = ea.emp_id and e.home_address = ea.address ) 中插入0还是1。

r'reverse mapping checking getaddrinfo for \S+ \[([^\]]+)\]'
相关问题