If you want to use the automatically generated ID from an INSERT
operation in MySQL as values for two subsequent fields in another SQL statement, you can store the generated ID in a variable and then use it in the subsequent INSERT
statements. Here's how you can achieve this:
-- Step 1: Create the first table with an auto-increment primary key
CREATE TABLE first_table (
id INT AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(255)
);
-- Step 2: Insert a row into the first table
INSERT INTO first_table (data) VALUES ('Some data');
-- Step 3: Get the ID of the inserted row and store it in a variable
SET @first_table_id := LAST_INSERT_ID();
-- Step 4: Use the retrieved ID to insert into the second table with two subsequent fields
CREATE TABLE second_table (
id INT AUTO_INCREMENT PRIMARY KEY,
first_table_id INT,
other_data1 VARCHAR(255),
other_data2 VARCHAR(255),
FOREIGN KEY (first_table_id) REFERENCES first_table(id)
);
-- Step 5: Insert into the second table using the retrieved ID
INSERT INTO second_table (first_table_id, other_data1, other_data2)
VALUES (@first_table_id, 'Other data 1 related to the first table', 'Other data 2 related to the first table');
In this example:
- We insert a row into
first_table
. - We retrieve the last inserted ID using
LAST_INSERT_ID()
and store it in the user-defined variable@first_table_id
. - We then use this variable
@first_table_id
to insert values intosecond_table
for two subsequent fieldsother_data1
andother_data2
.
This way, you're utilizing the generated ID from the first insert operation in the subsequent insert operations for the second table.