简体   繁体   中英

Use auto_incremented ID in same statement the ID is being created

I'm not sure how to formulate the title correctly. I'll try to elaborate, and make it understandable here.

I have a table with an auto_incremented ID (Primary Key). In the same table I have a guid-column. This guid is going to be an URL. So the guid will typically be something like http://www.example.com/path/path/ID

My question is this: Because the ID is auto-generated on INSERT, and I don't manually assign this, I dont know beforehand what the ID is going to be. How can I then assign the guid-value in the insert-statement, if I'm dependant on having the ID?

The solution I have at the moment is doing it with two statements:

INSERT INTO table (ID, guid) 
VALUES (null, null);

I will now have a row that looks something like this:

-------------
| ID | GUID |
-------------
| 1  | null |
-------------

I can then in another statement update this row with a statement like this;

UPDATE  table SET  guid = ID WHERE ID = 1;

(Might be off-syntax, but you get the point)

Is there any way to do this in "one go"? Where I can set the GUID based off of what the auto_incremented ID is going to be? So it would be something like this

INSERT INTO table (ID, guid) 
VALUES (null, ID);

I hope my question is understandable! I will clarify if it's still unclear. I don't know any better way to explain my question.

If the PK is autogenerated you don't need it in your insert query.

insert into table
(guid)
values
(your guid)

You of course have to generate the guid on your own and there are lots of ways to do that.

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