[QS] Insert update duplicated

Discussion in 'PHP' started by zinzinday, Oct 27, 2009.

  1. #1
    
    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!
     
    zinzinday, Oct 27, 2009 IP
  2. youngone324

    youngone324 Peon

    Messages:
    125
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    please explain more clearly,,,
     
    youngone324, Oct 27, 2009 IP
  3. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #3
    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):
     
    mastermunj, Oct 27, 2009 IP
  4. Gungz

    Gungz Peon

    Messages:
    65
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Only in MySQL or with PHP?
     
    Gungz, Oct 27, 2009 IP