I have two dependent tables as
CREATE TABLE posts
(
post_id int(11) unsigned NOT NULL AUTO_INCREMENT,
title varchar(255),
PRIMARY KEY(post_id)
) ENGINE=InnoDB
CREATE TABLE post_meta
(
post_id int(11) unsigned REFERENCES posts(post_id) ON DELETE CASCADE,
info varchar(255),
PRIMARY KEY(post_id)
) ENGINE=InnoDB
Question 1: After INSERTing into posts, post_meta does not accept value with error Duplicate entry XX for key 'PRIMARY. How should I modify the table structure?
Question 2: How can I set to create a corresponding row in post_meta upon INSERT INTO posts? I mean creating an empty row (only having id of the FK) in post_meta when creating a row in posts. In other words having the same number of rows in two columns without any INSERT into the second column.
Your current implementation looks as out of normalized form. Are you sure you need to keep the data separated to two different tables? Maybe
will do?
Speculating: if you’re doing it that way because of security issues then MySQL supports Column-level privileges.
If normalizing your data is unacceptable for some reasons then you can just make
post_idprimary key in both tables (don’t make it foreign key!) and add INSERT and DELETE triggers on tablepostswhich will insert or delete corresponding rows from post_meta.UPDATE
You said in comment that you can have multiple records in
post_metatable corresponding to single record inposts. That changes a lot:post_idin tablepost_meta. Primary key MUST be unique in table scope.post_metathen you shoud add a new (possibly auto_increment field) topost_metatable and use it as primary key. (Also, table can exist even without primary key but it’s against most DB guidelines)postsas I’ve already suggested. Another approach is using a stored procedure (and only stored procedure) for adding records toposts– and in this SP you can write some SQL to insert necessary records topost_meta.