MySQL - Insert comma separated list into normalize

2019-08-06 19:32发布

问题:

I have 3 tables in my database,

  • posts with the columns post_id, post_title, and post_text
  • tags with the columns tag_id and tag_text
  • post_tag with the columns post_id and tag_id

I want to write a stored procedure for creating a new post. This post may have any number of tags. If the tag does not exist yet, it should be added to the tags table.

Now my problem is, that I'm getting the tags as a comma separated list (e.g. "tag1,tag2,tag3"). What is the best approach to make one row in the table out of each of these values.

My ideas up until now were:

  • Splitting the post creation in multiple stored procedures and calling one for every tag.
  • Using some kind of explode function on the string in the DB and using a loop to insert every resulting tag (I don't even know if this is possible).
  • Dropping the stored procedure and putting together the whole statement as a string (I'd rather not do that).
  • Finding a way to bring MySQL to accept variable parameter lists.

Is there any other / better way to make this work, or what's the best approach to this problem?