Question

I have 3 tables:

category doesnt matter

item2cat: itemID|catID

item: id|name|desc

I want to list the items that are in the given category, but I don't know how to do it in a simple way. (With PHP and MySQL)

I need this table-structure because I want multiple categories to one item.

Was it helpful?

Solution

You probably want to join the item2cat table on your item table:

SELECT
  item.id
, item.name
, item.desc
FROM item
INNER JOIN item2cat ON item.id = item2cat.itemID
WHERE item2cat.catID = [category_id]

or for example

SELECT
  item.id
, item.name
, item.desc
, category.id
, category.name
FROM item
INNER JOIN item2cat ON item.id = item2cat.itemID
INNER JOIN category ON item2cat.catID = category.id
WHERE category.id IN ( [category_id], [category_id], [category_id])

UPDATE
If you changed your table IDs like this:

item (itemId, name, desc)
item2cat (itemId, categoryId)
category (categoryId, name, etc)

you could rewrite the first query like:

SELECT
  item.itemId
, item.name
, item.desc
FROM item
INNER JOIN item2cat USING( itemId )
WHERE item2cat.categoryId = [category_id]

Another advantage is that the id column of every table is now unambiguous.

OTHER TIPS

This one should be efficient and get all relevant items in a given category:

SELECT item.* 
   FROM item2cat
      JOIN item 
   ON item.id = item2cat.itemID
      and item2cat.catID = $categoryID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top