Given MySQL tables something like this1:
alpha (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
, beta_id INT NULL
, type_info INT NOT NULL
, CONSTRAINT fk_alpha_beta FOREIGN KEY (beta_id) REFERENCES beta (id)
) ENGINE=InnoDB;
beta (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
, type_info INT NOT NULL
) ENGINE=InnoDB;
My alpha table contains many rows, and I want to create corresponding rows in table beta, and store the ids in the alpha.beta_id
column.
I can create the rows in beta in one shot like this:
INSERT INTO beta (type_info)
SELECT type_info FROM alpha
WHERE beta_id IS NULL;
How can I do this in such a way that I can put the generated beta ids into the beta_id
columns of the corresponding rows in alpha?
The rows in beta do not have unique characteristics that would allow me to identify them retrospectively.
If it were only one row I was creating, I could use something like:
UPDATE alpha
SET beta_id=LAST_INSERT_ID()
WHERE beta_id IS NULL;
But that does not seem to be generalisable to multiple rows.
This question is vaguely similar, but it is using INSERT ... VALUES
and isn't applicable to a use case with INSERT ... SELECT
.
This question has similar requirements, and I know I can use ROW_COUNT
to see how many rows were inserted, but that doesn't give me a correspondence between the rows I added and the rows in alpha that they were created for.
I'm left with writing a non-SQL script that will pull all the information out, create the beta rows one at a time, and then update rows in alpha individually. But I would rather do this in-SQL, and it seems like a fairly obvious use case.
1. Obviously our actual schema is somewhat more complicated, but I have tried to boil it down to the information necessary to demonstrate the question.