简体   繁体   中英

SQL query to join two tables, adding new records if records missing

I have two tables, both with same data:

IP address | count

I need to combine the two tables into new one that contains data from both original tables.

  • IF there is a matching record in both tables, their count should be added.
  • IF there is a record that exists only in one table it gets copied over to the new table.

Let first table be called ip_data_january, second called ip_data_february and the one I am trying to create is ip_data_yearly. Thanks in advance.

1st insert only new ip addresses (with count starting at zero)

 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);

2nd update the count

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

..

3rd do this for all months

You can use ON DUPLICATE KEY UPDATE I Assume Unique index on IP_Address .. then

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;

If the IP_Data_Yearly table is empty, an INSERT with a subquery that aggregates count by IP should do the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM