Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: use the id of the row being inserted in the insert statement itself

I'm trying to some something like that:

INSERT INTO dir_pictures SET filename=CONCAT(picture_id,'-test');

picture_id is my primary key, auto-increment. Basically I'm trying to put the id of this insert statement, in the statement itself.

I'm sure it can be done with some extra PHP code or using more than one statements, but I was wondering if there is a quick and easy way to do it in one shot.

PS. The statement above always put '0-test'

like image 790
Nathan H Avatar asked Oct 28 '09 23:10

Nathan H


People also ask

How do I get the inserted row id in MySQL?

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

How do I get the last row inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

Which option can be used with insert statement in MySQL?

You can also use INSERT ... TABLE in MySQL 8.0. 19 and later to insert rows from a single table. INSERT with an ON DUPLICATE KEY UPDATE clause enables existing rows to be updated if a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY .

Which insert statement will add a row of data?

The INSERT command is used to add new data into a table. MySql will add a new row, once the command is executed.


2 Answers

Insert a record first. Then separate your statements with a semicolon and use LAST_INSERT_ID() to fetch the newly inserted autoincrement id. Execute in one go.

insert into dir_pictures .... ; 
update dir_pictures set filename=CONCAT(LAST_INSERT_ID(),'-test') where id = LAST_INSERT_ID()
like image 118
ChristopheD Avatar answered Oct 09 '22 08:10

ChristopheD


Just select the current auto_increment value for the table form the information_schema as part of your insert:

INSERT INTO dir_pictures SET filename=CONCAT((SELECT auto_increment FROM
information_schema.tables WHERE table_name='dir_pictures'), '-test')
like image 24
ataylor Avatar answered Oct 09 '22 08:10

ataylor