I have 3 tables called POSTS, HASHTAGS and POSTS_HASHTAGS_RELATION, as below.
CREATE TABLE POSTS(
post_id int unsigned NOT NULL AUTO_INCREMENT,
content varchar(200) NOT NULL,
PRIMARY KEY (post_id)
);
CREATE TABLE HASHTAGS(
hashtag_id int unsigned NOT NULL AUTO_INCREMENT,
hashtag varchar(40) NOT NULL,
PRIMARY KEY (hashtag_id)
);
CREATE TABLE POSTS_HASHTAGS_RELATION(
post_id int unsigned NOT NULL,
hashtag_id int unsigned NOT NULL,
PRIMARY KEY (post_id, hashtag_id)
);
When user posts, they select upto 20 hashtags from those saved in HASHTAGS. I send the hashtag_id(s) of these hashtags from front end as comma separated string to backend where it is converted to list in nodejs.
Firstly, is there a better approach to struture this?
Secondly, how do I insert variable number of rows to POSTS_HASHTAGS_RELATION in a single query?
INSERT INTO POSTS (content) VALUES ('bla bla bla bla');
SET @post_id = LAST_INSERT_ID();
INSERT INTO POSTS_HASHTAGS_RELATION (post_id, hashtag_id) VALUES (@post_id, 19), (@post_id, 41) ...;
// Something like this but the number of values can be between 1 and 20
If this has been answered befored, just guide me to that answer. I am unable to find anything relevant. I assume this is not a very unique problem.