Synchronize creation of rows between tables

All we need is an easy explanation of the problem, so here it is.

Lets say I have two tables, posts(id_pk,title) and posts_content(post_id_pk,blob). Whenever I create a row in posts, I want a complimentary row to be created in posts_content, with the same id. If I just use auto_increment on both, when two posts are created simultaneously, they might get switched. What is the correct way to do this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Let’s say you have this:

CREATE TABLE posts
(
    id int not null auto_increment,
    title varchar(100),
    primary key (id)
) ENGINE=InnoDB;
CREATE TABLE posts_content
(
    post_id int not null,
    blobdata blob,
    primary key (post_id),
    CONSTRAINT `FK_posts` FOREIGN KEY (`post_id`) REFERENCES posts (`id`)
) ENGINE=InnoDB;

You could perhaps run the two INSERTs like this:

START TRANSACTION;
INSERT INTO posts (title) VALUES ('some-title');
SET @GivenPostID = LAST_INSERT_ID();
INSERT INTO posts_content (post_id,blobdata)
VALUES (@GivenPostID,'oxbdsixds');
COMMIT;

Give it a Try !!!

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply