Database design for apps using “hashtags”

夙愿已清 提交于 2019-11-28 18:21:21

I would advise going with a typical many-to-many-relationship between messages and tags.

That would mean you need 3 tables.

  • One table for the messages themselves (minimal requirement: columns ID, UserID and message-content)
  • One table for the tags (minimal requirement here is: columns ID and tag-name)
  • And one last table tagMessagesRelations to make the connections between messages and tags (via foreign keys messageID and tagID)

That way you do not store a tag multiple times but only create a new relation to a message (if that tag already exists in the tag-table of course).

That then enables you to

  • easily count how many tags there are (SELECT COUNT(*) FROM tags)
  • you will only save each tag once and search for tags can be easily indexed
  • or count how many times a certain tag was used per user (for example:

SELECT COUNT(*) FROM tags INNER JOIN tagMessagesRelations ON tags.ID = tagMessagesRelations.tagID INNER JOIN messages ON tagMessagesRelations.messageID = messages.ID GROUP BY messages.UserID

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!