phpmysqlinsert-into

INSERT INTO or Update


My code updates same row multiple times in one query with values from another table. How to update or create a new record in one query? How to do that if there is no record "forum_users_posts_in" with matching data

userid 
idcat
idcustom
create a new record (t.posts = 1)

If such a record exists then update it only (t.posts = t2.sum_total)

UPDATE #__forum_users_posts_in AS t
            JOIN (
            SELECT
            userid, count(*) AS sum_total
            FROM
            #__forum_messages AS t2
            WHERE
            T2.thread = '.$topicId.' and hold = 0
            GROUP BY
            t2.userid
            ) AS t2 ON t.userid = t2.userid and (idcat = '.$cat->id.' or idcustom = '.$selectcustom1.')
            SET  t.posts =  t.posts + t2.sum_total

Solution

  • You can try this method to create or edit row

    INSERT INTO `table` (`columns`) VALUES
    (...)
    ON DUPLICATE KEY UPDATE
    `column` = VALUES (`column`);