List items by category

十年热恋 提交于 2019-12-06 05:52:05

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.

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