I have an application where a particular event updates my database with INSERT
s to two tables A
and B
. There is an additional association/link table AB
with foreign keys id_A
, id_B
to A
and B
that maps their many-to-many relationship. My question is how to best update AB
when one of the foreign keys isn't known to the application logic (in this case because it is an AUTO_INCREMENT
ID).
Additional details:
id_B
is set to AUTO_INCREMENT
, so its value is not known before the insert. B
is updated with a multi-row INSERT
; A
is a single row INSERT
. id_B
is a unique key but there are possible duplicates which are handled by an ON DUPLICATE KEY UPDATE
which replaces the old values with new ones. A
and B
are updated in the same transaction in response to the same event. My idea was to include all the insert statements in a stored procedure where the final INSERT
to AB
would get the values for id_B
from LAST_INSERT_ID()
but apparently this will only return the value for the first row in a multi-row insert: https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
I suppose a bonus would be if the logic to update AB
could be separated out into a trigger or a different statement from what is being used to update the parent tables.
Edit: response to comments.
Before the statement(s) used to insert your data into A
and B
place the following statement...
SET @before = ( SELECT MAX( id_B ) AS maxIDB
FROM B );
This will find the largest value of id_B
in B
at this moment. All subsequent insertions into B
will have a larger value than this. We can use this fact to our advantage.
After the above mentioned insert statement place the following statement...
INSERT INTO AB ( id_A,
id_B )
SELECT id_A_value,
B.id_B
FROM B
WHERE B.id_B > @maxIDB;
Note : By your above question I am assuming that id_A
is known. I am representing this value with id_A_value
.
This statement will insert into AB
rows containing the known value of id_A
and all of the freshly generated values of id_B
.
If you have any questions or comments, then please feel free to post a Comment accordingly.
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.