CREATE TABLE `data` ( `id` INT NOT NULL , `hits` INT NOT NULL , PRIMARY KEY ( `id` ) , INDEX ( `hits` ) ) ENGINE = MYISAM PHP: CREATE TABLE `data_store` ( `id` INT NOT NULL , `hits` INT NOT NULL , PRIMARY KEY ( `id` ) , INDEX ( `hits` ) ) ENGINE = MYISAM PHP: i want insert and update hits count from table data into table data_store if duplicated data_store.id then update data_store.hits = data_store.hits + data.hits Plz generator mysql command for me. Thanks for your enthrusiasm!
first of all, data table has id as primary hence it can not have duplicate key. considering it is not primary and can have duplicate entries. following set of queries will do the needful for you. DROP TEMPORARY TABLE IF EXISTS t1; CREATE TEMPORARY TABLE t1 SELECT id, SUM(hits) AS hits FROM data GROUP BY id; UPDATE data_store A JOIN t1 B ON A.id = B.id SET A.hits = A.hits + B.hits; INSERT IGNORE INTO data_store SELECT A.id, A.hits FROM t1 A LEFT JOIN data_store B ON A.id = B.id WHERE B.id IS NULL; Code (markup):