Naterade
Naterade

Reputation: 2675

Best way to implement keywords or tags in Mysql

So I have a database of recipes and I want to associate keywords or tags with each meal, such as 'Chinese', 'Italian', 'Low-card' etc. The user never submits keywords so I have full control. Which of the following do you think is the best approach..

A) I could have a column in the meal table filled with keywords followed by commas. Italian, healthy, etc. Then I could grab the results from a single row on a single column and then use PHP to parse the results and do the heavy lifting.

B) I could have a keyword table with each row containing the meal_id then a single keyword. I could then query for all keywords with that id.

Or is there a better way to do implement keywords such as a fulltext??

Upvotes: 1

Views: 3533

Answers (4)

vadchen
vadchen

Reputation: 1462

B is better for when you'll search by tag is will be trivial task. With A you'll have to work much harder. Also with B you can always get comm-separated tags by using GROUP_CONCAT(tag)

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

If you with keywords mean something like tags, that are used on many sites, here on StackOverflow for instance. Then you would have three tables. One table with the meals, one table with the keywords, and one table to link both of them together. That way you can efficiently list all meals associated with a certain keyword, with a simple SQL-query.

Upvotes: 9

Jeremy Harris
Jeremy Harris

Reputation: 24549

I would definitely use a separate table for keywords to ensure your database is normalized.

Upvotes: 1

Wes Crow
Wes Crow

Reputation: 2967

Definitely go with B. This is the more normalized option and will be the easiest to work with. Otherwise your code will have to parse the query results.

Upvotes: 0

Related Questions