Reputation: 35
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.
Upvotes: 2
Views: 889
Reputation: 1437
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
Upvotes: 0
Reputation: 23799
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.
Upvotes: 2