List items by category

感情迁移 提交于 2020-01-02 13:11:00

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2217030/list-items-by-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!