In MySQL, how can I use the autoincrement value in another column at the time of the INSERT?

ⅰ亾dé卋堺 提交于 2020-01-15 14:27:09

问题


I am looking to have the automagically set autoincrement included in another column during the insert. For example in a table where ID is the autoincrement and Name is the other column, I'd like to do something like

`INSERT INTO Names (Name) VALUES (CONCAT("I am number ",ID));`

Currently, I do the INSERT without Name, then I have to immediately after do an UPDATE using $mysqli->insert_id.

I don't want to query the table in advance because, as small a time as it may be, another record could get inserted between getting the next autoincrement value and the insertion. A trigger could work, but it seems like overkill. I just want to know if I can reference the autoincrement within the insertion.

Many thanks!


回答1:


The problem is not as easy as it seems. In a BEFORE INSERT trigger, the autoincrement value hasn't been generated yet (NEW.autoinc_column is 0), and in an AFTER INSERT trigger, it is not possible anymore to change the values to be inserted.

With MyISAM tables, you could check the table definition for the next AUTO_INCREMENT value:

DELIMITER //    

    CREATE TRIGGER inserName BEFORE INSERT ON name FOR EACH ROW
    BEGIN
        DECLARE next_ai INT;
        SELECT auto_increment INTO next_ai
          FROM information_schema.tables
          WHERE table_schema = DATABASE() AND table_name = 'name';
        SET NEW.name = CONCAT("I am number ", next_ai);
    END //

DELIMITER ;

I believe this could work too with InnoDB tables if innodb_autoinc_lock_mode = 0 (not the case by default), but I am not sure (because of possible concurrency issues).

But if the value to concat is always the same, you probably had better using a view such as:

CREATE VIEW names_v AS SELECT id, CONCAT("I am number ", id) AS name FROM names;



回答2:


I've also recently been facing this problem and although it might not be the best solution, what I did could be a viable alternative for your case. In my case it was sufficient. You could use a AFTER INSERT trigger to update the field with the value refering to the pseudo-variable NEW. This will probably give you a bit more flexibility. I needed to fill a field with a string that was computed using the value from the auto increment column. The trigger reads the NEW pseudo-variable, computes the necessary values and executes the UPDATE. It still does require two high level write-acesses to the database, but all are done consecutively and without the need for further interaction with the client application (effectively, one single insert statement being sent from the client application, being followed by the implicit update).



来源:https://stackoverflow.com/questions/17266442/in-mysql-how-can-i-use-the-autoincrement-value-in-another-column-at-the-time-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!