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

StackOverflow https://stackoverflow.com/questions/17619698

문제

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!

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top