简体   繁体   中英

Is it possible to get the ID of the row being inserted *in the statement*?

I want to have the image I'm uploading have the ID of the row it belongs to as the name (eg 42.jpg ) to ensure uniqueness.

Is it possible to get this in the middle of the query? Or do I have to get the ID after then update the row?

You could first insert an empty row (with a null image and filename.) You can retrieve the last inserted ID with LAST_INSERT_ID() .

After that, you can update the row with the image and the file name based on the ID.

If id is AUTO_INCREMENT column in the table you're inserting... no, the automatically assigned value is not available during statement execution. And the value isn't available when a BEFORE INSERT trigger is fired.

The value assigned to the row is only available after the INSERT statement completes.

Immediately following a successful insert, SELECT LAST_INSERT_ID() (equivalent library function) can retrieve the value assigned.

As another option, you could consider emulating an Oracle sequence object, using a separate table with an AUTO_INCREMENT column, and LAST_INSERT_ID. If you get that as a unique id before you do the INSERT, you could supply the value in the INSERT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM