good way to store tags in relational database when there are variable numbers of tags associated with each piece of information

冷暖自知 提交于 2019-12-24 03:15:05

问题


I want to store sentences that can be tagged with variable numbers of tags in an SQL relational database. So, I may have a sentence such as

'As the sun sets slowly in the west, we bid you a fine farewell.'

tagged with the following tags:

'farewell', 'goodbye', 'amiable'

The number of tags for a sentence can vary. In the example given here, there are three tags.

What would be a sensible way to organise this type of information in a relational database? What tables etc. would be reasonable?

Thanks!


回答1:


You have a many-to-many relationship. Make three tables: sentence, tag and sentence_tag. The sentence and tag tables will each have a primary key id field and sentence_tag will have a sentence_id field and a tag_id field. To find the tags for a sentence with id = $sID,

SELECT tag_name FROM tags WHERE id IN (SELECT tag_id FROM sentence_tag WHERE sentence_id = $sID);


来源:https://stackoverflow.com/questions/17619698/good-way-to-store-tags-in-relational-database-when-there-are-variable-numbers-of

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