Saving multiple categories with one item

database-design, php, sql

Solution

You don't store multiple categories in one field, you create a separate table to assign categories to each item. Similar to this:

-- create your table to store items/products
create table items
(
  id int,  -- this will be the PK
  name varchar(10)
);

insert into items values
(1, 'product1'),
(2, 'product2');

-- create your table to store categories
create table categories
(
  id int,  -- this will be the PK
  name varchar(50)
);

insert into categories values
(1, 'color'),
(3, 'material'),
(6, 'size');

-- create your join table to assign the categories to each item
-- this table will have a foreign key relationship to the items and categories table
create table items_categories
(
  item_id int,   -- both fields will be the PK
  category_id int
);

insert into items_categories values
(1,  1),
(2,  3),
(2,  6);

Then you will query the data by joining the tables:

select i.id itemid,
  i.name item,
  c.name category
from items i
left join items_categories ic
  on i.id = ic.item_id
left join categories c
  on ic.category_id = c.id

See SQL Fiddle With Demo

Problem

I'm building a website where you add items with multiple categories. what is the best way to store multiple categories in one field and still keep the field searchable?

Original source