我有两张表,都有相同的数据:
IP address | count
我需要将两个表合并为一个包含两个原始表中数据的新表。
让第一个表称为ip_data_january,第二个称为ip_data_february,我尝试创建的是ip_data_yearly。提前谢谢。
答案 0 :(得分:2)
第一次只插入新的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次为所有月份做这个
答案 1 :(得分:2)
您可以使用ON DUPLICATE KEY UPDATE 我假设IP_Address的唯一索引..然后
INSERT INTO ip_data_yearly (ip_adress)
SELECT IP_Address FROM IP_Data_January
UNION ALL SELECT IP_Address FROM IP_Data_February
ON DUPLICATE KEY UPDATE `count`=`count`+1;
答案 2 :(得分:1)
如果IP_Data_Yearly
表为空,则INSERT
具有通过IP聚合计数的子查询应该可以解决问题:
INSERT INTO IP_Data_Yearly
SELECT IP_Address, SUM(Count)
FROM (
SELECT IP_Address, Count FROM IP_Data_January
UNION ALL SELECT IP_Address, Count FROM IP_Data_February
) IPCombined
GROUP BY IP_Address