views:

48

answers:

2

Hello

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.

+2  A: 

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.

Jacco
Oh thanks, in my solution I screwed up the where part.
Richard Mre
Why using a LEFT OUTER JOIN if you only want to list items in a given cateogry? using an INNER JOIN should be much more efficient and would avoid unnecessary full-scans
Saggi Malachi
@Saggi Malachi, thanks, updated
Jacco
A: 

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
Saggi Malachi