I have this alogirthm problem, in terms of creating mysql tables, let me explain the scenario:
I have a a posts table:
Posts{id, user_id,image,tag,date}
each post can only have on tag! ONLY
Do I need to have another table to store tags! I can understand if each post has more than one tag, you’d have to create another table for it to store the tags! but with this its only one!
i.e.
If I wanted to get all the posts with tag ‘DOG’ I would use:
select all posts where tag=DOG
do you think this is wrong or bad? I’m so confused!
If posts in your system will really only ever need to have one tag, then technically you can just hold the tag on the Post record. You shouldn’t, though: For example, what happens when you have 250000 posts about dogs, and decide to rename the “Dog” tag to “Canine”?
A better idea is to create a Tag table and put a foreign key to it on the Post table. For example:
But just in case you’re really faced, someday, with a scenario in which a Post can have multiple Tags…
Then you’re describing a model in which
PostsandTagsexist in what’s called a Many-to-Many relationship: a given tag can be associated with any number of posts, and a given post can be associated with any number of tags.Now you not only need a separate table for Tags, but a relationship table in between that relates posts to tags. For example:
You would then select all posts with the “Dog” tag like so: