MySql相同字段但不同日期数据的数据表如何合并?

有两个表如ea_user_info,和ea_user_info0508,

其中ea_user_info0508是早期的备份数据,

因为备份所以没有在后续的程序中写入新数据,

但ea_user_info是相当于新表,

写入了部分数据,现在需要查询过往历史,就需要合并两个表,

1.保留原表不动,新建一个同字段的表ea_user_info_merge;

CREATE TABLE `ea_user_info_merge` LIKE `ea_user_info`;

2.对字段ID设置自增属性,保证后续写入数据自增ID;

ALTER TABLE `ea_user_info_merge` MODIFY COLUMN `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;

3.合并数据并写入数据。我们将逻辑拆分为两部分:

  1. 取出最新表 ea_user_info 的所有数据。
  2. 取出备份表 ea_user_info0508 中那些“在最新表中不存在”的数据。
  3. 将两者合并后按 user_id 排序。
INSERT INTO `ea_user_info_merge` (
    `user_id`, `phone_num`, `phone_sp`, `phone_addr`, `nick_name`, `user_status`, 
    `reg_type`, `reg_times`, `phone_model`, `app_version`, `app_platform`, 
    `app_channel`, `device_id`, `region_code`, `app_code`, `sm_result`, 
    `zj_type`, `zs_total_recharge`, `sb_total_recharge`, `total_consume`, 
    `total_income`, `total_balance`, `buy_hy_times`, `buy_ai_times`, 
    `last_model`, `last_code`, `last_version`, `register_time`, `last_time`, 
    `online_time`, `create_time`, `update_time`
)
SELECT 
    `user_id`, `phone_num`, `phone_sp`, `phone_addr`, `nick_name`, `user_status`, 
    `reg_type`, `reg_times`, `phone_model`, `app_version`, `app_platform`, 
    `app_channel`, `device_id`, `region_code`, `app_code`, `sm_result`, 
    `zj_type`, `zs_total_recharge`, `sb_total_recharge`, `total_consume`, 
    `total_income`, `total_balance`, `buy_hy_times`, `buy_ai_times`, 
    `last_model`, `last_code`, `last_version`, `register_time`, `last_time`, 
    `online_time`, `create_time`, `update_time`
FROM (
    -- 第一部分:获取最新表的所有记录
    SELECT * FROM `ea_user_info`
    
    UNION ALL
    
    -- 第二部分:获取备份表中存在,但最新表中不存在的 user_id
    SELECT * FROM `ea_user_info0508` t_old
    WHERE NOT EXISTS (
        SELECT 1 FROM `ea_user_info` t_new 
        WHERE t_new.user_id = t_old.user_id
    )
) AS combined
ORDER BY user_id ASC;

4.检查数据量:

SELECT COUNT(*) FROM `ea_user_info_merge` WHERE 1

5.备份原表 ea_user_info,修改ea_user_info_merge为ea_user_info。

 

posted @ 2026-01-12 17:14  coderjim  阅读(2)  评论(0)    收藏  举报

更多知识请点击——

www.7017online.xyz