表数据迁移

将A表数据迁移到B表:

  1. 两张表字段一样,并且插入全部数据;

    INSERT INTO 目标表 SELECT * FROM 来源表;
    -- 将table_02表的数据全部迁移到table_01
    INSERT INTO table_01 SELECT * FROM table_02;
    
  2. 插入指定字段;

    -- 字段要一致
    INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表;
    -- 指定字段,table_02后面还可以使用where条件
    INSERT INTO table_01 (user_name, user_id) SELECT name as user_name, user_id FROM table_02;
    
  3. 只导入目标表中不存在的记录;

    INSERT INTO 目标表 (字段1, 字段2, ...) 
    SELECT 字段1, 字段2, ... FROM 来源表
    WHERE id NOT IN 
    ( 
    SELECT id FROM 目标表 
    )
    
    -- 过滤table_01表中已存在的user_id的数据
    INSERT INTO table_01 ( user_name, user_id,  gmt_create,  is_deleted ) 
    SELECT user_name, user_id, NOW(), 0 FROM table_02
    WHERE
    user_id NOT IN 
    (
    SELECT user_id FROM table_01
    )
    

你可能感兴趣的:(数据库)