问题
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