MySQL INSERT …ON DUPLICATE UPDATE - Adds one to the autoincrement

后端 未结 4 568
星月不相逢
星月不相逢 2020-12-09 11:32

I keep track of all the http_user_agents that visit me, with a simple hit counter. The below insert the http_user_agent in the DB, this field is Case Insensitive and is Uniq

4条回答
  •  温柔的废话
    2020-12-09 11:35

    You can first calculate the maximum number of inserted rows and add 1 to it,

    (SELECT MAX(`id`)+1 FROM `tblRefHttpUsersAgent`)
    

    then alter the table AUTO_INCREMENT using some variables SET @NEW_ID and PREPARE / EXECUTE statements.

    here is a simple solution for the same problem and below is the finished version if you like the solution of your own specific problem:

        $sql = 'SET @NEW_AI = (SELECT MAX(`id`)+1 FROM `tblRefHttpUsersAgent`);
                        SET @ALTER_SQL = CONCAT("ALTER TABLE `tblRefHttpUsersAgent` AUTO_INCREMENT =", @NEW_AI);
                        PREPARE NEWSQL FROM @ALTER_SQL;
                        EXECUTE NEWSQL;';
    
        $sql .= 'INSERT INTO `db_agency_cloud`.`tblRefHttpUsersAgent` SET `http_users_agent` = :UsersAgent, `created_ts` = NOW() ON DUPLICATE KEY UPDATE `hits` = `hits` + 1';
    

提交回复
热议问题