insert sql id as next sql filed in mysql

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 into second_table for two subsequent fields other_data1 and other_data2.

This way, you're utilizing the generated ID from the first insert operation in the subsequent insert operations for the second table.

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值