gpt4 book ai didi

mysql - SQL查询连接两个表,如果记录丢失则添加新记录

转载 作者:行者123 更新时间:2023-11-29 04:23:27 25 4
gpt4 key购买 nike

我有两个表,都有相同的数据:

IP address | count

我需要将这两个表合并成一个包含两个原始表中数据的新表。

  • 如果两个表中都有匹配的记录,则应添加它们的计数
  • 如果有一条记录只存在于一个表中,它会被复制到新表中。

将第一个表命名为 ip_data_january,第二个表命名为 ip_data_february,而我要创建的表是 ip_data_yearly。提前致谢。

最佳答案

第一次只插入新的 ip 地址(计数从零开始)

 insert into ip_data_yearly (ip_adress, count) 
(select distinct ip_address, '0' from jan_table
where ip_addess not in (select ip_adress from ip_data_yearly);

第二次更新计数

update ip_data_yearly y 
set count= count +
(select count(j.ip_adress) from jan_table where j.ip_adress=y.ip_adress);

..

第 3 个月都这样做

关于mysql - SQL查询连接两个表,如果记录丢失则添加新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17087760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com