简体   繁体   中英

MySQL/PHP Relating Database Content by Keywords

I read here a lot but this is the first I've asked a question.

I'm developing a website, with LAMP, that is essentially all about user submitted articles. I would like to relate some articles together by tags (or keywords) so that I may show a viewer some content that is related.

I had an idea of creating a field within the MySQL database table, where the articles resides, called "tags" that consists of a comma delimited list of keywords. They would relate to the article and describe it's content in some fashion. Yet I discovered this wasn't a bright idea as I wouldn't be able to index this very well.

So, how would I go about this, any ideas?

ps. Just seen the little box to the right on this site called, "Similar Questions" what I'm trying to achieve is a lot like that...

It's a many-to-many relationship, and can be modelled using a separate table with a foreign key to the article ID, and a column for a tag. Multiple tags are added to an article by adding multiple rows to the table.

For example, if you have two articles where:

  • Article 1 has tags "foo" and "bar" and
  • Article 2 has tags "bar" and "baz"

then the table might look like this:

article_tags
article_id   tag
1            foo
1            bar
2            bar
2            baz

You can even store the tag names in a separate table:

tags
id  name
1   foo
2   bar
3   baz

article_tags
article_id   tag_id
1            1
1            2
2            2
2            3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM