可以使用 MySQL 的事务来保证同时向两张表插入多条数据时的数据一致性。事务可以保证多个操作要么全部成功,要么全部失败,以此来保证数据的一致性。

具体实现步骤如下:

  1. 开启事务
BEGIN;
  1. ask_questions 表中插入数据
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, '问题1', '问题描述1', 0, 0, 0, 0, 0, 0, 0, 1, 0, NOW(), NOW()),
       (2, 3, '问题2', '问题描述2', 0, 0, 0, 0, 0, 0, 0, 1, 0, NOW(), NOW());
  1. 获取插入的主键 id
SELECT LAST_INSERT_ID();
  1. ask_answers 表中插入数据,question_id 字段与 ask_questions 表中的主键对应
INSERT INTO ask_answers (question_title, question_id, user_id, content, supports, oppositions, comments, device, status, adopted_at, created_at, updated_at) 
VALUES ('问题1', LAST_INSERT_ID(), 1, '回答1', 0, 0, 0, 1, 0, NULL, NOW(), NOW()),
       ('问题2', LAST_INSERT_ID(), 2, '回答2', 0, 0, 0, 1, 0, NULL, NOW(), NOW());
  1. 提交事务
COMMIT;

这样就可以保证同时向两张表插入多条数据时的数据一致性。如果其中一条插入失败,整个事务会回滚,保证数据的完整性。

MySQL 多表同时插入数据并保持数据一致性

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

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