4

I was just wondering if this is the most efficient way to use categories:

---------------------------------
| ID   | ITEM      | CATEGORY   |
---------------------------------
| 1    | COOKIES   | FOOD       |
| 2    | CAKE      | FOOD       |
| 3    | WATER     | DRINK      |
| 4    | PEANUTS   | FOOD       |
| 5    | PEPSI     | DRINK      |
---------------------------------
 ↑ int  ↑ text      ↑ text        <- [ type of column ]

Then my query is:

SELECT * FROM `table` WHERE category='FOOD';
1
  • I want to know if thats the most efficient way to structure a category column. Ive seen some databases with numbers to represent the category names. Is that more efficient? Commented Mar 7, 2012 at 9:55

3 Answers 3

7

I think if you change a little bit, for example, category column in categories ID,

`---------------------------------
| ID   | ITEM      | CATEGORY   |
---------------------------------
| 1    | COOKIES   | 1          |
| 2    | CAKE      | 1          |
| 3    | WATER     | 2          |
| 4    | PEANUTS   | 1          |
| 5    | PEPSI     | 2          |

Plus a categories table

--------------------
| ID   | ITEM      | 
--------------------
| 1    | FOOD  
| 2    | DRINK     

AND query:

SELECT * FROM `table` WHERE category=1;   (or 2)
Sign up to request clarification or add additional context in comments.

3 Comments

Please, remove quotes for int values!
both. more efficiently because you can run complexe queries (if you need) it's a relationship database. It's better to run queries on int or date fields not on text or varchar fields. Are several reasons..
not the most flexible approach because this way you cannot have multiple categories for a single item; something like stackoverflow.com/a/48324559/191246 would be a more standard approach
0

Do you know about normalization forms? You have duplicate data in your table. It more beautiful to create 2 tables: item, category.

item: (id, item, category_id)
category: (id, name)

Comments

0

You can use enum instead of text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.