So I started to write a forum, because I want to learn a little SQL (MySQL).
So firstly, I have a posts table, and there are a post_id and topic_id columns.
But, on the other side I have a topics table.
In the topics table I also have a last_post_id and topic_id, too !
So they are referencing to each other.
So the question is: When a user creates a topic (and the same time writes the first post), how to INSERT these id’s effectively??
Because now I have to do the following steps:
-
Insert topic related data (topic title..etc, insert last_post_id =0 cause I dont know this value here), then retrieve topic_id
-
Insert post data (text, username.., topic_id), and retieve this particular post_id
- Update topics table, with the retrieved post_id (set
last_post_id).
Isn’t it too long, tedious, uneffective..?
Thanks for your time. My english is not the best.. sry.
You could do it using a single transaction, but the basic idea is the same. You need to insert the new topic before having
topic_id, and you need to insert the new post before havinglast_post_id. With your current tables, there’s no way around that.You could also use a
TRIGGERthat automatically updates thelast_post_idfield when a new record is added toposts. That doesn’t change the number of queries executed, but it would be handled transparently by MySQL itself.Also, the point raised by mu is too short in his answer about setting
last_post_idtoNULLis a good idea.