Please I am trying to insert the last ID into a different column of the same row in mysql. This is what i have tried
Insert Query
"INSERT INTO table(char,name) VALUES (LAST_INSERT_ID(),'KOKO')"
This is the Output
ID | char | name |
1 | 0 | KOKO |
HOWEVER, I expect that when a row is inserted the column char
will insert the ID
value as well; What i expect
ID | char | name |
1 | 1 | KOKO |
Please is there something i am doing wrong. Will be glad to know, thanks in advance
You can't use LAST_INSERT_ID()
and insert in the same transaction because LAST_INSERT_ID()
do not know value of the last insert id before insert
Please try to use update:
INSERT INTO table(char,name) VALUES (0,'KOKO')
UPDATE table
SET char = LAST_INSERT_ID()
WHERE ID = LAST_INSERT_ID()
According to MySQL documentation the LAST_INSERT_ID()
returns a generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement. Therefore you need this sequence: insert -> get last insert id -> update. Here is code:
INSERT INTO table (char, name) VALUES (0, 'KOKO')
UPDATE table SET `char` = LAST_INSERT_ID() WHERE `ID` = LAST_INSERT_ID()
But it turns out that the column char
duplicates column ID
which possibly indicates wrong DB structure.
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.