可以使用 MySQL 的事务来同时插入两张表的数据,确保数据的完整性和一致性。具体步骤如下:

  1. 开启事务

在执行插入操作之前,使用 START TRANSACTION 语句开启一个事务。

  1. 插入 ask_questions 表数据

向 ask_questions 表插入多条数据,保证每条数据都符合表结构和约束关系,并且获取插入数据的主键 id。

  1. 插入 ask_answers 表数据

向 ask_answers 表插入多条数据,保证每条数据都符合表结构和约束关系,同时将 question_id 字段设置为上一步获取的主键 id。

  1. 提交事务

如果插入操作都成功,使用 COMMIT 语句提交事务,否则使用 ROLLBACK 语句回滚事务。

示例代码如下:

START TRANSACTION;

INSERT INTO ask_questions (user_id, category_id, title, description, price, hide, answers, views, followers, collections, comments, device, status, created_at, updated_at)
VALUES (1, 2, 'Question 1', 'Description 1', 10, 0, 0, 0, 0, 0, 0, 1, 0, NOW(), NOW()),
       (2, 3, 'Question 2', 'Description 2', 20, 0, 0, 0, 0, 0, 0, 1, 0, NOW(), NOW());

SET @question_id = LAST_INSERT_ID();

INSERT INTO ask_answers (question_title, question_id, user_id, content, supports, oppositions, comments, device, status, adopted_at, created_at, updated_at)
VALUES ('Question 1 Answer 1', @question_id, 1, 'Answer 1 Content', 0, 0, 0, 1, 0, NULL, NOW(), NOW()),
       ('Question 1 Answer 2', @question_id, 2, 'Answer 2 Content', 0, 0, 0, 1, 0, NULL, NOW(), NOW()),
       ('Question 2 Answer 1', @question_id, 1, 'Answer 3 Content', 0, 0, 0, 1, 0, NULL, NOW(), NOW());

COMMIT;
MySQL 多表同时插入数据:ask_questions 和 ask_answers 表示例

原文地址: http://www.cveoy.top/t/topic/lO2m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录